我在 Stack Overflow 上找到了这个答案:
length is constant which is used to find out the array storing capacity not the number of elements in the array
示例:
int a[] = new int[5]
a.length
始终返回 5,这称为 an 的容量 数组,所以 length 总是返回 CAPACITY。但是"number of elements in the array is called size"
例子:
int a[] = new int[5] a[0] = 10
将导致
a.size = 1
和a.length = 5
。
size()
适用于集合,length
适用于 java 中的数组
( Difference between size and length methods? , 2017-09-06)
由于这个答案获得了 5 个赞成票,我认为它是正确的。但是在 Java 中实际上没有数组的大小属性。我知道 ArrayLists 有一个方法。但是,如果使用普通数组,a.size
怎么可能等于 1?我错过了什么吗?
最佳答案
你是对的,答案是错误的:Java 数组没有 .size
属性,只有 .length
。
为了给答案的作者带来疑问,我怀疑他们试图解释 ArrayList
如何在内部使用数组。
ArrayList
实际上通常有一个.size
成员在元素数组旁边:
class ArrayList<T> implements ... {
private T[] elements;
private int size;
...
}
关于Java 数组 : Attribute size?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46073467/