在 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
有些日子比其他日子更繁忙。繁忙的一天是指有 5 只或更多鸟造访过你的花园。
实现BirdWatcher.getBusyDays()方法,返回繁忙日子的数量:
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
BirdWatcher birdCount = new BirdWatcher(birdsPerDay);
birdCount.getBusyDays();
// => 2