问题描述
我在堆栈溢出中找到了这个答案:
I found this answer on Stack Overflow:
示例:
int a[] = new int[5]
a.length
始终返回5,这称为 数组,因此length始终返回CAPACITY.但是
a.length
always returns 5 which is called the capacity of an array, so length always returns the CAPACITY. but
示例:
int a[] = new int[5]
a[0] = 10
将得到a.size = 1
和a.length = 5
.
size()
适用于集合,length
适用于Java中的数组
size()
works with collection, length
works with arrays in java
(大小和长度方法之间的区别?,2017年9月06)
(Difference between size and length methods? , 2017-09-06)
由于该答案获得了五次投票,我认为这是正确的.但是,实际上Java中没有数组的size属性.我知道有一个ArrayLists的方法.但是,如果使用普通数组,a.size
怎么等于1?我想念什么吗?
As this answer received five upvotes I thought it is correct. But there is actually no size attribute for arrays in Java. I know there's a method for ArrayLists. However, how can a.size
be equal to one if normal arrays are used? Am I missing something?
推荐答案
您是正确的,答案是错误的:Java数组没有.size
属性,只有.length
.
You are correct and the answer is mistaken: Java arrays don't have a .size
attribute, only .length
.
为了给答案的作者带来疑问的好处,我怀疑他们正在尝试解释ArrayList
在内部如何使用数组.
To give the answer's author the benefit of the doubt, I suspect they are trying to explain how an array gets used internally by an ArrayList
.
ArrayList
实际上实际上通常在元素数组旁边还有一个.size
成员 :
An ArrayList
does in fact typically have a .size
member alongside the element array:
class ArrayList<T> implements ... {
private T[] elements;
private int size;
...
}
这篇关于Java数组:属性大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!