ArrayList默认初始容量和扩容源码

本文探讨了ArrayList在JDK 1.6中的默认初始容量为10,并且在元素超出容量时,会进行扩容操作,将新容量设置为原容量的1.5倍。在JDK 1.8版本中,这一机制保持不变。

版本:JDK 1.6 的源码

ArrayList默认初始容量 源码

在这里插入图片描述
The size of the ArrayList (the number of elements it contains).
数组列表的大小(包含元素的数量)。

Constructs an empty list with an initial capacity of ten.
构造一个初始容量为10的空列表。

总结 :
ArrayList内部封装了一个默认长度为10的数组。
当超出长度时,集合内部会自动生成一个新的数组。
将原数组中的元素复制到新数组中,在将新元素添加到新数组。

接下来看ArrayList扩容 源码:


    /**
     * Appends the specified element to the end of this list.
     * 将指定的元素附加到列表的末尾。
     * 
     *
     * @param e element to be appended to this list
     * 添加到此列表中的E元素
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
   
   
	ensureCapacity(size + 1);  // Increments modCount!!增量modCount
	elementData[size++] = e;
	return true;
    }



    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer.
     */
    private transient Object[] elementData;

	
    /**
     * Increases the capacity of this <tt>ArrayList</tt> instance, if
     * necessary, to ensure that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     * 增加<tt>ArrayList</tt>实例的容量
     * 如有必要,确保它至少可以容纳元素的数量由最小容量参数指定。  
     * @param   minCapacity   the desired minimum capacity
     */
    public void ensureCapacity
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值