数据是第一级对象的说法比较明显,有第一级就有第二级。
第一级是指什么?
无论使用哪种类型的数组,数组的标识符其实只是一个引用,指向堆中的一个真实对象。
这个对象(数组)保存着指向其他对象的引用。第一级指的是对象(数组)的引用,这个引用指向一个对象数组。
class BerylliumSphere {
}
public class ArrayOptions {
public static void main(String[] args) {
// Arrays of objects:
BerylliumSphere[] a; // Local uninitialized variable
BerylliumSphere[] b = new BerylliumSphere[5];
// The references inside the array are
// automatically initialized to null:
System.out.println("b: " + Arrays.toString(b));
BerylliumSphere[] c = new BerylliumSphere[4];
for (int i = 0; i < c.length; i++)
if (c[i] == null) // Can test for null reference
c[i] = new BerylliumSphere();
// Aggregate initialization:
BerylliumSphere[] d = { new BerylliumSphere(), new BerylliumSphere(),
new BerylliumSphere() };
// Dynamic aggregate initialization:
a = new BerylliumSphere[] { new BerylliumSphere(),
new BerylliumSphere(), };
// (Trailing comma is optional in both cases)
System.out.println("a.length = " + a.length);
System.out.println("b.length = " + b.length);
System.out.println("c.length = " + c.length);
System.out.println("d.length = " + d.length);
a = d;
System.out.println("a.length = " + a.length);
// Arrays of primitives:
int[] e; // Null reference
int[] f = new int[5];
// The primitives inside the array are
// automatically initialized to zero:
System.out.println("f: " + Arrays.toString(f));
int[] g = new int[4];
for (int i = 0; i < g.length; i++)
g[i] = i * i;
int[] h = { 11, 47, 93 };
// Compile error: variable e not initialized:
// !System.out.println("e.length = " + e.length);
System.out.println("f.length = " + f.length);
System.out.println("g.length = " + g.length);
System.out.println("h.length = " + h.length);
e = h;
System.out.println("e.length = " + e.length);
e = new int[] { 1, 2 };
System.out.println("e.length = " + e.length);
}
}
输出:
b: [null, null, null, null, null]
a.length = 2
b.length = 5
c.length = 4
c:= [pdmtest.cl.BerylliumSphere@3fbefab0, pdmtest.cl.BerylliumSphere@133c5982, pdmtest.cl.BerylliumSphere@5f186fab, pdmtest.cl.BerylliumSphere@3d4b7453]
d.length = 3
a.length = 3
f: [0, 0, 0, 0, 0]
f.length = 5
g.length = 4
h.length = 3
e.length = 3
e.length = 2
注意第一笔输出 b: [null, null, null, null, null]
这个输出有两层含义
数组b指向一个BerylliumSphere引用的数组,其实并没有对象在数组中,数组是空的。但仍然可以访问数组的大小,因为b指向一个合法的对象。
c:表示数组的引用,指向堆中的一个真实数组对象这是第一级
再看第五行c:=的输出 的内容是数组对象的引用。这是第二级