Java 数组:属性大小? [英] Java array: Attribute size?
问题描述
我在 Stack Overflow 上找到了这个答案:
<块引用><块引用>length 是常数,用于找出数组存储容量而不是数组中元素的数量
示例:
int a[] = new int[5]
a.length
总是返回 5,称为一个的容量数组,所以长度总是返回容量.但是
数组中元素的个数称为大小"
示例:
int a[] = new int[5][0] = 10
将导致 a.size = 1
和 a.length = 5
.
size()
适用于集合,length
适用于 java 中的数组
(尺寸和长度方法的区别? , 2017-09-06)
由于这个答案收到了五个赞成票,我认为这是正确的.但是实际上 Java 中没有数组的 size 属性.我知道 ArrayLists 有一个方法.但是,如果使用普通数组,如何 a.size
等于 1?我错过了什么吗?
你是对的,答案是错误的:Java 数组没有 .size
属性,只有 .length
.
为了让答案的作者受益匪浅,我怀疑他们正试图解释 ArrayList
如何在内部使用数组.
ArrayList
实际上通常在元素数组旁边有一个 .size
成员:
class ArrayList实现 ... {私有 T[] 元素;私有整数大小;...}
I found this answer on Stack Overflow:
length is constant which is used to find out the array storing capacity not the number of elements in the array
Example:
int a[] = new int[5]
a.length
always returns 5 which is called the capacity of an array, so length always returns the CAPACITY. but"number of elements in the array is called size"
Example:
int a[] = new int[5] a[0] = 10
Will result in
a.size = 1
anda.length = 5
.
size()
works with collection,length
works with arrays in java
(Difference between size and length methods? , 2017-09-06)
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?
You are correct and the answer is mistaken: Java arrays don't have a .size
attribute, only .length
.
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
.
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 数组:属性大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!