天天看点

jdk源码ArrayList

类关系图

jdk源码ArrayList

有些抽象类没有展示。图片来源忘了,侵立删

本来想自己写一篇的,但是发现了一个写的比较全面的博客

ArrayList

https://www.cnblogs.com/skywang12345/p/3308556.html

这里记录一下自己的理解

和Vector不同,ArrayList中的操作不是线程安全的!所以,建议在单线程中才使用ArrayList,而在多线程中可以选择Vector或者CopyOnWriteArrayList

ArrayList的底层是array存储object[]数组,对数组进行扩展,类的声明和属性

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

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = ;//数组初始化时的大小

    /**
     * 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.5倍实现代码

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> );//这里可以看出
        if (newCapacity - minCapacity < )
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > )
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
           

继续阅读