在 Java 中,陣列可以把多個相同型別的值存放在同一個結構裡。 和其他資料結構不同,陣列一旦建立,大小就固定了。 你可以用索引把元素指定到陣列中,也可以用索引從陣列中取出元素。 Java 的陣列使用從 0 開始的索引:第一個元素的索引是 0,第二個元素的索引是 1,以此類推。
以下是初始化陣列的標準語法:
type[] variableName = new type[size];
type 是陣列中元素的型別,可以是基本型別(例如int)或類別(例如String)。
size 是這個陣列可以容納的元素數量(之後無法更改)。
建立陣列之後,元素會被初始化為預設值(通常是0、false或null)。
// Declare array with explicit size (size is 2)
int[] twoInts = new int[2];
陣列也可以用簡寫語法定義,同時建立陣列並設定它的值:
// Two equivalent ways to declare and initialize an array (size is 3)
int[] threeIntsV1 = new int[] { 4, 9, 7 };
int[] threeIntsV2 = { 4, 9, 7 };
由於編譯器現在可以判斷陣列會有多少個元素,因此長度可以省略。
陣列元素可以用方括號索引的語法來指定和存取:
// Assign second element by index
twoInts[1] = 8;
// Retrieve the second element by index and assign to the int element
int secondElement = twoInts[1];
如果存取的索引超出陣列的有效範圍,會導致IndexOutOfBoundsException。
你可以呼叫陣列實體的方法或屬性來操作陣列,也可以使用Arrays類別中定義的靜態方法(通常只用於泛型程式碼)。
length 屬性會保存陣列的長度。
可以這樣存取:
int arrayLength = someArray.length;
Java 也提供了一個實用的工具類別 java.util.Arrays,裡面有許多實用的陣列相關方法(例如Arrays.equals)。
Java 也支援多維陣列,例如 int[][] arr = new int[3][4];,這非常實用。
陣列同時也是一種_集合_,這表示除了用索引存取值之外,你還可以用 for-each 迴圈疊代它的_所有_值:
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
for(char vowel: vowels) {
// Output the vowel
System.out.print(vowel);
}
// => aeiou
如果你想更精確控制要疊代哪些值,可以使用 for 迴圈:
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
for (int i = 0; i < 3; i++) {
// Output the vowel
System.out.print(vowels[i]);
}
// => aei
你是個熱愛賞鳥的人,會記錄過去七天內有多少鳥造訪你的花園。
你有六項任務,全都和造訪你花園的鳥的數量有關。
為了方便比較,你總是會把上週的數量副本放在手邊,分別是:0、2、5、3、7、8 和 4。實作BirdWatcher.getLastWeek()方法,回傳上週的數量:
BirdWatcher.getLastWeek();
// => [0, 2, 5, 3, 7, 8, 4]
實作BirdWatcher.getToday()方法,回傳今天有多少鳥造訪你的花園。鳥的數量是依日期排序的,第一個元素是最早那天的數量,最後一個元素則是今天的數量。
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
BirdWatcher birdCount = new BirdWatcher(birdsPerDay);
birdCount.getToday();
// => 1
實作BirdWatcher.incrementTodaysCount()方法,將今天的數量加一:
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
BirdWatcher birdCount = new BirdWatcher(birdsPerDay);
birdCount.incrementTodaysCount();
birdCount.getToday();
// => 2
實作BirdWatcher.hasDayWithoutBirds()方法,如果有某一天沒有任何鳥造訪花園,就回傳true;否則回傳false:
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
BirdWatcher birdCount = new BirdWatcher(birdsPerDay);
birdCount.hasDayWithoutBirds();
// => true
實作BirdWatcher.getCountForFirstDays()方法,回傳從這週開始以來造訪你花園的鳥的數量,但將計算範圍限制在從這週開頭算起的指定天數內。
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
BirdWatcher birdCount = new BirdWatcher(birdsPerDay);
birdCount.getCountForFirstDays(4);
// => 14
有些日子比其他日子更忙碌。所謂忙碌的一天,是指有五隻或更多鳥造訪你的花園。
實作BirdWatcher.getBusyDays()方法,回傳忙碌的天數:
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
BirdWatcher birdCount = new BirdWatcher(birdsPerDay);
birdCount.getBusyDays();
// => 2