我记得,在Java 8之前,默认容量ArrayList是10.
令人惊讶的是,对default(void)构造函数的注释仍然说: Constructs an empty list with an initial capacity of ten.
来自ArrayList.java:
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
...
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
Run Code Online (Sandbox Code Playgroud) 我看到了ArrayList的java doc,发现ArrayList的初始容量是10.
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this(10);
}
Run Code Online (Sandbox Code Playgroud)
我认为如果它是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();
}
Run Code Online (Sandbox Code Playgroud)
10号后面有没有明确的原因?