ArrayList的自动扩充机制,ArrayList扩充机制
分享于 点击 48648 次 点评:42
ArrayList的自动扩充机制,ArrayList扩充机制
用一道选择题作为本文的开始吧!
ArrayList list = new ArrayList(20);中的list扩充几次
-
0
-
1
-
2
-
3
1、ArrayList的默认初始容量为10,当然也可以自定义指定初始容量,随着动态的向其中添加元素,其容量可能会动态的增加,那么扩容的公式为: 新容量 = 旧容量/2 + 旧容量 + 1 比如:初始容量为4,其容量的每次扩充后的新容量为:4->7->11->17->26->... 即每次扩充至原有基础的1.5倍
ArrayList的构造函数总共有三个: (1)ArrayList()构造一个初始容量为0 的空列表。在public add add(E e)方法添加一个元素到空的ArrayList对象中时候, 同时将初始容量赋值为
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {//如果容量为空, 则赋值初始容量为16
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;//修改次数加一
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
(2)ArrayList(Collection<? extends E> c)构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。 (3)ArrayList(int initialCapacity)构造一个具有指定初始容量的空列表。 调用的是第三个构造函数,直接初始化为大小为20的list,没有扩容,所以选择A
另外与之类似的还有,
2、HashMap的初始大小为16,增长时,直接容量翻番,如源代码。
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);//原容量2倍
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
3、Vector的初始大小为10,如果没有指定每次增长的大小,则默认是翻倍增长。
相关文章
- 暂无相关文章
用户点评