且构网

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

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

更新时间:2023-11-29 19:08:04

如果您使用 arr = new Employee[100] 分配一个新数组,则该数组的大小 (arr.length) 将是 100.它有 100 个元素.所有元素最初都是空的(因为这是一个对象引用数组),但仍然有 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.

如果您执行诸如 list = new 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 个项目,但这是一个内部实现细节,并且列表向您显示其内容为不存储的物品".只有当你真的执行 list.add(something) 时,你才会在列表中看到项目.

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.