英文:
What happens when there are less elements in ArrayList than its capacity?
问题
ArrayList的容量设定为10,我向其中添加了5个元素。它们在内存中占据5个元素的大小还是10个元素的大小?
英文:
Say capacity is 10, I add 5 elements to ArrayList. Would they take 5 or 10 elements size in memory?
答案1
得分: 4
javadoc指出:
> 每个 ArrayList
实例都有一个容量。容量是用于存储列表中元素的数组的大小。它始终至少与列表大小一样大。当元素被添加到 ArrayList
中时,其容量会自动增长。增长策略的详细信息没有特定的规定,只知道添加一个元素的均摊时间成本是恒定的。
基于上述内容:
> 当 ArrayList
中的元素少于其容量时会发生什么?
考虑到支持数组的大小即为“容量”,数组中将会有未使用的插槽。
(实现确保这些未使用的插槽包含 null
,以避免任何内存泄漏。)
> 假设容量为10,我向 ArrayList
中添加了5个元素。它们在内存中占用5个还是10个元素的大小?
大小将是10个对象引用的大小,因为 ArrayList
持有对象的引用……而不是实际的元素对象本身。
英文:
The javadoc states:
> 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.
Based on the above:
> What happens when there are less elements in ArrayList
than its capacity?
Given that the backing array's size is the "capacity", there will be unused slots in the array.
(The implementation ensures that those unused slots contain null
to avoid any memory leaks.)
> Say capacity is 10, I add 5 elements to ArrayList
. Would they take 5 or 10 elements size in memory?
The size would be the size of 10 object references, since an ArrayList
holds references to objects ... not the actual element objects themselves.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论