我们可以使用数组列表的公共方法size()来确定数组列表<E>的长度,比如
ArrayList<Integer> arr = new ArrayList(10);
int size = arr.size();
类似地,我们可以使用length属性确定Array对象的长度
String[] str = new String[10];
int size = str.length;
ArrayList的size()方法是在ArrayList类中定义的,那么Array的length属性是在哪里定义的呢?
数组是java中的特殊对象,它们有一个简单的名为length的属性,这个属性是final。
数组没有“类定义”(你在任何.class文件中都找不到它),它们是语言本身的一部分。
10.7. Array Members
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
资源:
JLS -阵列
它基本上是“特殊的”,有自己的字节码指令:arraylength。这个方法:
public static void main(String[] args) {
int x = args.length;
}
编译成字节码,如下所示:
public static void main(java.lang.String[]);
Code:
0: aload_0
1: arraylength
2: istore_1
3: return
所以它不像普通字段那样被访问。事实上,如果你试图把它当作一个正常的字段,就像这样,它会失败:
// Fails...
Field field = args.getClass().getField("length");
System.out.println(field.get(args));
所以不幸的是,JLS对每个数组类型都有一个公共最终字段长度的描述有点误导人:(