问题描述
ArrayList
中的参数 (int initialCapacity)
是什么意思,我以为是元素的数量,但是当我这样做时它不起作用:
What's meant by parameter (int initialCapacity)
in an ArrayList
, I thought it's the number of elements but it didn't work when I did this:
public class MyClass {
private ArrayList<Integer> arr;
public MyClass(int n_elements) {
arr = new ArrayList<Integer>(n_elements);
}
}
推荐答案
是初始容量,即ArrayList
开始分配的items个数,作为items的内部存储空间.
It's the initial capacity, i.e. the number of items that ArrayList
will allocate to begin with as the internal storage of items.
>
ArrayList
可以包含任意数量的项目"(只要你有足够的内存),当进行大量的初始插入时,你可以告诉 ArrayList
分配一个更大的当它尝试为下一项分配更多空间时,存储开始时不会浪费 CPU 周期.
ArrayList
can contain "any number of items" (as long you have the memory for it) and when doing large initial insertions you can tell ArrayList
to allocate a larger storage to begin with as to not waste CPU cycles when it tries to allocate more space for the next item.
示例:
ArrayList list = new ArrayList<Integer>(2);
list.add(1); // size() == 1
list.add(2); // size() == 2, list is "filled"
list.add(3); // size() == 3, list is expanded to make room for the third element
这篇关于数组列表中的参数(int 初始容量)是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!