看了ArrayList的java doc,发现ArrayList的初始容量是10。
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this(10);
}
我认为如果它是 2 的任何幂都有意义,但为什么是 10?
我还检查了 HashMap 的初始容量,它是 16,这是有道理的。
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
table = new Entry[DEFAULT_INITIAL_CAPACITY];
init();
}
数字 10 背后有什么具体原因吗?
最佳答案
ArrayList
是简单的增长数组。当尝试添加元素时,缓冲区大小超出了,它只是在增长。所以初始大小可以是任何正值。
1 太少了。即使有一些元素,我们也会有一些调整大小的操作。
100 将失去空间。
所以,10 是妥协。为什么是 10 而不是 12 或 8?第一个提示是,分析了典型用例,这是性能损失和空间损失之间的最佳匹配。但是,我认为,看到 Sun 的原始代码,它没有被深入分析,它是一个任意的“不太小,也不太大”的数字。
关于java - 为什么ArrayList的默认容量是10?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10794890/