Java基础--初步分析ArrayList源码

简介

ArrayList作为Java集合容器,在我们的开发过程中是非常常见的。
ArrayList继承了AbstractList,实现了List、RandomAccess、Cloneable以及Serializable接口,支持快速访问、复制以及序列化。
ArrayList底层是基于数组的存储结构,支持null,可以通过索引进行随机访问,所以ArrayList的查询效率非常高。
但是数组的长度是固定的,默认长度是10,当ArrayList里的元素增加到一定数量时会进行扩容,生成新的数组并把之前的数组引用指向新的数组。

部分源码

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 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 = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

构造方法

ArrayList支持三种构造方法
1、ArrayList(int initialCapacity)–指定初始化创建ArrayList的大小
2、ArrayList()–默认构造方法
3、ArrayList(Collection<? extends E> c)–传入一个Collection对象,内部通过Arrays.copyOf()转换成ArrayList

扩容

ArrayList每次add元素的时候都会检查数组容量够不够,如果容量不够的话会进行扩容操作,
newCapacity = oldCapacity + (oldCapacity >> 1);
扩容之后的容量大小为之前的1.5倍

持续更新中…

猜你喜欢

转载自blog.csdn.net/qrainly/article/details/95200998