数组类型
前言
学到这里,终于到令人激动人心的数组了。
Java 中数组的创建过程其实类似于 C++ 中动态开辟数组:
public class Hello {
public static void main(String[] args) {
int[] arr = new int[5];
arr[0] = 3;
System.out.println(arr[0]);
}
}
Java 数组中的几个特点:
- 数组默认初始化为默认值:
int[]
是0
,float
是0.0
,布尔型是false
- 数组一旦创建,大小不可改变。
- 可以用
数组变量
.length
来获取长度
public class Hello {
public static void main(String[] args) {
int[] arr_int = new int[5];
float[] arr_float = new float[5];
boolean[] arr_boolean = new boolean[5];
System.out.println(arr_int[0]); // 0
System.out.println(arr_float[0]); // 0.0
System.out.println(arr_boolean[0]); // false
System.out.println(arr_int.length); // 通过内置的属性来获取长度
}
}
热知识:Java 数组是引用类型并且从 0
开始,如果访问超出索引将会报错。
定义数组时,直接指定初始化的元素:
public class Hello {
public static void main(String[] args) {
int[] arr = new int[] {1, 2, 3, 4, 5}; // 编译器会自动推算出数组的大小
for (int i = 0; i < arr.length; i ++) { // 遍历数组并打印。
System.out.print(arr[i] + " ");
} // 结果:1 2 3 4 5
}
}
还可以进一步缩写:
public class Hello {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i ++) {
System.out.print(arr[i] + " ");
}
}
}
对于数组是引用,可以看这样一个例子来加深印象:
public class Hello {
public static void main(String[] args) {
int[] arr;
arr = new int[] {1, 3, 4};
System.out.println(arr.length);
arr = new int[] {2, 4, 5, 1, 4, 5};
System.out.println(arr.length);
}
}
这里在内存中其实开出了两段数组,当为arr
赋值的时候,前一个数组并没有改变,只是arr
的引用指向了新的数组。
字符串数组
字符串数组是引用型,通过索引改变数组中的字符串也只是改变了该索引的引用:
public class Hello {
public static void main(String[] args) {
String[] arr = {"ABC", "XYZ", "zoo"};
arr[1] = "cat";
System.out.println(arr[1]);
System.out.println(arr.length);
}
}
所以,对于下面的代码,你可以做出自己的解释吗?
public class Hello {
public static void main(String[] args) {
String[] names = {"ABC", "XYZ", "zoo"};
String s = names[1];
names[1] = "cat";
System.out.println(s); // s是"XYZ"还是"cat"?
}
}
我觉得,结果很显然,是"XYZ"