ArrayList:大小如何增加? [英] ArrayList: how does the size increase?

查看:32
本文介绍了ArrayList:大小如何增加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a basic question on Java ArrayList.

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

When ArrayList is declared and initialized using the default constructor, memory space for 10 elements is created. Now, when I add an 11th element, what happens? Will new memory space be created with 20 (or more) element capacity (this requires copying elements from 1st memory location to new location) OR some thing else?

我检查了此处.但我没有找到答案.

I checked here. But I didn't find an answer.

请分享知识.谢谢.

推荐答案

创建了一个新数组并复制了旧数组的内容.这就是您在 API 级别所知道的全部内容.引用 文档(我的重点):

A new array is created and the contents of the old one are copied over. That's all you know at the API level. Quoting from the docs (my emphasis):

每个 ArrayList 实例都有一个容量.容量是用于存储列表中元素的数组的大小.它始终至少与列表大小一样大.随着元素被添加到 ArrayList,它的容量会自动增长.除了添加元素的摊销时间成本不变外,没有指定增长政策的细节.

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 的)实际发生的情况而言,在他们的情况下,您可以在源代码中看到血腥的细节.但是当然,依赖特定实现的细节通常不是一个好主意......

In terms of how it actually happens with a specific implementation of ArrayList (such as Sun's), in their case you can see the gory details in the source. But of course, relying on the details of a specific implementation isn't usually a good idea...

这篇关于ArrayList:大小如何增加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆