我们可以使用数组列表的公共方法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属性是在哪里定义的呢?
它基本上是“特殊的”,有自己的字节码指令: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对每个数组类型都有一个公共最终字段长度的描述有点误导人:(
尽管这不是对问题的直接回答,但它是对.length vs .size()参数的补充。我正在研究与这个问题相关的东西,所以当我遇到它时,我注意到这里提供的定义
公共最终字段长度,它包含数组的组件数。
并不“完全”正确。
字段长度包含可放置组件的可用位置的数量,而不是数组中存在的组件的数量。所以它表示分配给数组的总可用内存,而不是内存被填满了多少。
例子:
static class StuffClass {
int stuff;
StuffClass(int stuff) {
this.stuff = stuff;
}
}
public static void main(String[] args) {
int[] test = new int[5];
test[0] = 2;
test[1] = 33;
System.out.println("Length of int[]:\t" + test.length);
String[] test2 = new String[5];
test2[0] = "2";
test2[1] = "33";
System.out.println("Length of String[]:\t" + test2.length);
StuffClass[] test3 = new StuffClass[5];
test3[0] = new StuffClass(2);
test3[1] = new StuffClass(33);
System.out.println("Length of StuffClass[]:\t" + test3.length);
}
输出:
Length of int[]: 5
Length of String[]: 5
Length of StuffClass[]: 5
然而,数组列表的.size()属性确实给出了列表中元素的数量:
ArrayList<Integer> intsList = new ArrayList<Integer>();
System.out.println("List size:\t" + intsList.size());
intsList.add(2);
System.out.println("List size:\t" + intsList.size());
intsList.add(33);
System.out.println("List size:\t" + intsList.size());
输出:
List size: 0
List size: 1
List size: 2
数组是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 -阵列