相关疑难解决方法(0)

在Java 8中,为什么ArrayList的默认容量现在为零?

我记得,在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)

java arraylist java-8

88
推荐指数
3
解决办法
6万
查看次数

为什么ArrayList 10的默认容量?

我看到了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号后面有没有明确的原因?

java collections arraylist

35
推荐指数
4
解决办法
5万
查看次数

标签 统计

arraylist ×2

java ×2

collections ×1

java-8 ×1