为什么ArrayList的10的默认容量? [英] Why is the default capacity of ArrayList 10?

查看:2281
本文介绍了为什么ArrayList的10的默认容量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到的ArrayList在Java doc和发现ArrayList的初始容量为10。

I saw the java doc for ArrayList and found that the initial capacity of ArrayList is 10.

 /**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
this(10);
}

我想会更有意义,如果它是2的幂,但为什么10?

I think it would make sense if it were any power of 2, but why 10?

我还检查的HashMap的初始容量,它的16这是有道理的。

I also checked HashMap's initial capacity, and it's 16 which makes sense.

/**
 * 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指定的任何原因?

Is there any specify reason behind the number 10?

推荐答案

的ArrayList 简单日益增多的。当尝试添加元素,并且超出了缓冲区的大小,它只是增长。因此初始尺寸可以是任意的正值。

The ArrayList is simple growing array. When trying to add element, and the buffer size is exceeded, it is simply growing. So the initial size can be any positive value.

1.将是太少了。即使有几个要素,我们将有一些调整操作。

The 1 would be too little. Even with a few elements we will have a few resize operations.

100将是空间的损失。

The 100 would be a loss of space.

因此​​,10是折衷。为什么10,而不是12或8?第一个暗示,即典型应用案例进行了分析,这是失去了绩效之间,失去了空间的最佳选择。不过,我觉得,看到太阳的原来的code,它没有分析如此深刻,它是一个任意的不能太小,没有太大'号。

So, the 10 is compromise. Why 10 and not 12 or 8? First hint, that the typical use cases were analysed and this is the best fit between lost of performance and lost of space. However, I think, seeing the Sun's original code, that it wasn't analysed so deeply and it is an arbitrary 'not too small, not too big' number.

这篇关于为什么ArrayList的10的默认容量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆