java - ArrayList:大小如何增加?

标签 java arrays arraylist collections

我有一个关于 Java ArrayList 的基本问题。

ArrayList 使用默认构造函数声明和初始化时,会创建 10 个元素的内存空间。现在,当我添加第 11 个元素时,会发生什么?是否会创建具有 20 个(或更多)元素容量的新内存空间(这需要将元素从第一个内存位置复制到新位置)或其他什么?

我查看了 Java 1.4.2 的 ArrayList API 文档。但我没有找到答案。

请分享知识。 谢谢。

编辑:新链接:

最佳答案

创建一个新数组,并复制旧数组的内容。这就是您在 API 级别所知道的全部内容。引自 the docs (我的重点):

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

ArrayList 的特定实现(例如 Sun 的)实际发生的情况而言,您可以在源代码中看到血淋淋的细节。但当然,依赖特定实现的细节通常不是一个好主意...

关于java - ArrayList:大小如何增加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4450628/

相关文章:

java - 覆盖函数中的抽象

c - 移动字符串数组中的元素并用零填充

php - 查找多维数组中的重复值

java - 如何将两个按字典顺序排列的字符串 ArrayList 合并到一个新的第三个 ArrayList 中?

java - org.openqa.selenium.StaleElementReferenceException : stale element reference: element is not attached to the page document

java - 如何为多个级别创建 Hibernate Criteria

java - 当 max-size-policy 为 USED_HEAP_SIZE 时,Hazelcast 驱逐无法与 Spring 一起使用。它与 max-size-policy 作为 PER_NODE 一起正常工作

java - 在 Asynctask 的 onPostExecute 中获取空对象引用?

php - 如何在 php 中写出所有可能的单词?

java - 为什么此代码会产生 IndexOutOfBoundsException?