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

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

问题描述

看了ArrayList的java文档,发现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?第一个提示,分析了典型用例,这是性能损失和空间损失之间的最佳匹配.但是,我认为,看到Sun的原始代码,它没有分析得那么深入,并且是一个随意的不太小,不太大"的数字.

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天全站免登陆