我们可以使用数组列表的公共方法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属性是在哪里定义的呢?


当前回答

关键字长度就像定义的数据字段。在数组中使用时,可以使用它来访问数组中有多少元素。对于String[],我们可以调用String类中定义的length()方法。对于ArrayList,我们可以使用ArrayList中定义的size()方法。注意,当创建ArrayList<>(capacity)的数组列表时,该数组列表的初始size()为零,因为没有元素。

其他回答

数组是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 -阵列

它在Java语言规范中定义:

数组类型的成员都是以下类型: 公共最终字段长度,它包含数组的组件数。长度可以为正或零。

由于数组类型的数量是无限的(每个类都有一个对应的数组类型,然后还有多维数组),它们不能在类文件中实现;JVM必须在运行中完成它。

关键字长度就像定义的数据字段。在数组中使用时,可以使用它来访问数组中有多少元素。对于String[],我们可以调用String类中定义的length()方法。对于ArrayList,我们可以使用ArrayList中定义的size()方法。注意,当创建ArrayList<>(capacity)的数组列表时,该数组列表的初始size()为零,因为没有元素。

它基本上是“特殊的”,有自己的字节码指令: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对每个数组类型都有一个公共最终字段长度的描述有点误导人:(

回答这个问题,数组的长度属性是在哪里定义的?在一个特殊的Object头中。

通过JOL很容易看到

 int [] ints = new int[23];
 System.out.println(ClassLayout.parseInstance(ints).toPrintable());

输出的其中一行将是:

OFFSET  SIZE      TYPE DESCRIPTION
16       4        (object header)   17 00 00 00 (00010111 00000000 00000000 00000000) (23)

通常对象有两个头(mark和klass),数组有一个头,总是占用4个字节的长度,因为size是int型。