且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数组列表的容量和数组的大小之间的区别

更新时间:2023-11-29 18:45:46

如果您分配一个新的数组 ARR =新员工[100] ,即数组的大小( arr.length )将是100,有100个元素。所有的元素都是最初为null(因为这是对象引用数组),不过,也有100元。

If you allocate a new array with arr = new Employee[100], the size of that array (arr.length) is going to be 100. It has 100 elements. All the elements are initially null (as this is an array of object references), but still, there are 100 elements.

如果你做的东西像名单=新的ArrayList<员工>(100),并尝试检查则为list.size(),你会得到0有列表中没有的元素。

If you do something like list = new ArrayList <Employee>(100), and try to check list.size(), you'll get 0. There are no elements in the list.

在内部,这是真的,在的ArrayList 分配足够的地方放了100个项目之前,它需要扩大产能,但是这是一个内部实现细节,而列表presents其内容为你无物品存放。只有当你真正做 list.add(东西),你就会有列表中的项目。

Internally, it's true that the ArrayList allocates enough place to put 100 items before it needs to extend its capacity, but that's an internal implementation detail, and the list presents its content to you as "no items stored". Only if you actually do list.add(something), you'll have items in the list.

所以,虽然名单提前分配存储的API与它通信的程序会告诉您有在里面没有任何项目。其内部数组中的空项目不提供给你 - 你不能找回它们或改变它们

So although the list allocates storage in advance, the API with which it communicates with the program tells you there are no items in it. The null items in its internal array are not available to you - you cannot retrieve them or change them.