Java array: Attribute size?

折月煮酒 提交于 2020-01-13 19:39:32

问题


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 and a.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?


回答1:


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;
    ...
}



回答2:


Arrays are initialized upon declaration, hence their size is always equal to their length.

int[] array = new int[5];
for (int i : array) System.out.println(i);
System.out.println(array[4]);

will print 5 times "0" for the loop, then "0" again. Notice no exception for the array[4]: this element exists.

The same is not true for ArrayLists.

ArrayList<Integer> list = new ArrayList<>(5);
// no output, because no elements are contained
for (int i : list) System.out.println(i);
// Exception: no such element
System.out.println(list.get(4));



回答3:


However, how can a.size be equal to one if normal arrays are used? Am I missing something?

ArrayList internally uses array and it keep growing the length of the array dynamically as you keep adding elements to it.

The size method checks how many actually elements present in the array and returns that count.

If you look at the source code of array list it maintains a size variable and increments it when you add an elements

public void add(int index, E element) {
393         rangeCheckForAdd(index);
394 
395         ensureCapacity(size+1);  // Increments modCount!!
396         System.arraycopy(elementData, index, elementData, index + 1,
397                          size - index);
398         elementData[index] = element;
399         **size++;**
400     }

However there is no such wrapper on array and you are directly operating on arrays, hence the difference.



来源:https://stackoverflow.com/questions/46073467/java-array-attribute-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!