集合源码(一)| ArrayList源码剖析

学习源码,应该是一件认真与钻研的功课,点滴积累。

package java.util;  
  
public class ArrayList extends AbstractList  
        implements List, RandomAccess, Cloneable, java.io.Serializable  
{  
    //
    private static final long serialVersionUID = 8683452581122892189L;  
  
    //  
    private static final int DEFAULT_CAPACITY = 10;  
  
    // 
    private static final Object[] EMPTY_ELEMENTDATA = {};  
  
    // 
    private transient Object[] elementData;  
  
    // 
    private int size;  
  
/**************** Constructor ***********************/  
  
    //
    public ArrayList(int initialCapacity) {  
        super();  
        if (initialCapacity < 0)  
            throw new IllegalArgumentException("Illegal Capacity: "+  
                                               initialCapacity);  

        this.elementData = new Object[initialCapacity];
    }  
    
    //
    public ArrayList() {  
        super();  
        this.elementData = EMPTY_ELEMENTDATA;
    }  
  
    //  
    public ArrayList(Collection c) {  
        elementData = c.toArray(); 
        size = elementData.length;  
         
        if (elementData.getClass() != Object[].class)  
            elementData = Arrays.copyOf(elementData, size, Object[].class);  
    }  
  
/******************* Array size *************/  
  
    //  
    public void trimToSize() {  
        modCount++;  
        //  
        if (size < elementData.length) {  
            elementData = Arrays.copyOf(elementData, size);  
        }  
    }  
  
    // 
    public void ensureCapacity(int minCapacity) {  
        int minExpand = (elementData != EMPTY_ELEMENTDATA)  
            // any size if real element table  
            ? 0  
            // larger than default for empty table. It's already supposed to be  
            // at default size.  
            : DEFAULT_CAPACITY;  
  
        if (minCapacity > minExpand) {  
            ensureExplicitCapacity(minCapacity);  
        }  
    }  
  
    private void ensureCapacityInternal(int minCapacity) {  
    //
        if (elementData == EMPTY_ELEMENTDATA) {  
        //  
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);  
        }  
    //  
        ensureExplicitCapacity(minCapacity);  
    }  
      
    //
    private void ensureExplicitCapacity(int minCapacity) {  
        modCount++; // 
  
        //  
        if (minCapacity - elementData.length > 0)  
            grow(minCapacity);  
    }  
  
    // 
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;  
  
    // 
    private void grow(int minCapacity) {  
        // overflow-conscious code  
        int oldCapacity = elementData.length;  
        int newCapacity = oldCapacity + (oldCapacity >> 1); 
        if (newCapacity - minCapacity < 0)  
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)  
            newCapacity = hugeCapacity(minCapacity); 
        // minCapacity is usually close to size, so this is a win:  
        elementData = Arrays.copyOf(elementData, newCapacity);  
    }  
  
    private static int hugeCapacity(int minCapacity) {  
        if (minCapacity < 0) // overflow  
            throw new OutOfMemoryError();  
        return (minCapacity > MAX_ARRAY_SIZE) ?  
            Integer.MAX_VALUE :  
            MAX_ARRAY_SIZE;  
    }  
  
    // 
    public int size() {  
        return size;  
    }  
  
    // 
    public boolean isEmpty() {  
        return size == 0;  
    }   
  
/****************************** Search Operations *************************/  
  
    // 
    public boolean contains(Object o) {  
        return indexOf(o) >= 0;  
    }  
  
    //  
    public int indexOf(Object o) {  
        if (o == null) {  
            for (int i = 0; i < size; i++)  
                if (elementData[i]==null)  
                    return i;  
        } else {  
            for (int i = 0; i < size; i++)  
                if (o.equals(elementData[i]))  
                    return i;  
        }  
        return -1;  
    }  
  
    // 
    public int lastIndexOf(Object o) {  
        if (o == null) {  
            for (int i = size-1; i >= 0; i--)  
                if (elementData[i]==null)  
                    return i;  
        } else {  
            for (int i = size-1; i >= 0; i--)  
                if (o.equals(elementData[i]))  
                    return i;  
        }  
        return -1;  
    }  
  
/******************************* Clone *********************************/  
  
    //克隆函数  
    public Object clone() {  
        try {  
            @SuppressWarnings("unchecked")  
                ArrayList v = (ArrayList) super.clone();  
        //将当前ArrayList的全部元素拷贝到v中  
            v.elementData = Arrays.copyOf(elementData, size);  
            v.modCount = 0;  
            return v;  
        } catch (CloneNotSupportedException e) {  
            // this shouldn't happen, since we are Cloneable  
            throw new InternalError();  
        }  
    }  
  
/********************************* toArray *****************************/  
  
    /** 
    * 返回一个Object数组,包含ArrayList中所有的元素 
    * toArray()方法扮演着array-based和collection-based API之间的桥梁 
    */  
    public Object[] toArray() {  
        return Arrays.copyOf(elementData, size);  
    }  
  
    //返回ArrayList的模板数组  
    @SuppressWarnings("unchecked")  
    public  T[] toArray(T[] a) {  
    //如果数组a的大小 < ArrayList的元素个数,  
    //则新建一个T[]数组,大小为ArrayList元素个数,并将“ArrayList”全部拷贝到新数组中。  
        if (a.length < size)  
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());  
  
    //如果数组a的大小 >= ArrayList的元素个数,  
    //则将ArrayList全部拷贝到新数组a中。  
        System.arraycopy(elementData, 0, a, 0, size);  
        if (a.length > size)  
            a[size] = null;  
        return a;  
    }  
  
/******************** Positional Access Operations ********************/  
  
    @SuppressWarnings("unchecked")  
    E elementData(int index) {  
        return (E) elementData[index];  
    }  
  
    //获取index位置的元素值  
    public E get(int index) {  
        rangeCheck(index); //首先判断index的范围是否合法  
  
        return elementData(index);  
    }  
  
    //将index位置的值设为element,并返回原来的值  
    public E set(int index, E element) {  
        rangeCheck(index);  
  
        E oldValue = elementData(index);  
        elementData[index] = element;  
        return oldValue;  
    }  
  
    //将e添加到ArrayList中  
    public boolean add(E e) {  
        ensureCapacityInternal(size + 1);  // Increments modCount!!  
        elementData[size++] = e;  
        return true;  
    }  
  
    //将element添加到ArrayList的指定位置  
    public void add(int index, E element) {  
        rangeCheckForAdd(index);  
  
        ensureCapacityInternal(size + 1);  // Increments modCount!!  
    //将index以及index之后的数据复制到index+1的位置往后,即从index开始向后挪了一位  
        System.arraycopy(elementData, index, elementData, index + 1,  
                         size - index);   
        elementData[index] = element; //然后在index处插入element  
        size++;  
    }  
  
    //删除ArrayList指定位置的元素  
    public E remove(int index) {  
        rangeCheck(index);  
  
        modCount++;  
        E oldValue = elementData(index);  
  
        int numMoved = size - index - 1;  
        if (numMoved > 0)  
        //向左挪一位,index位置原来的数据已经被覆盖了  
            System.arraycopy(elementData, index+1, elementData, index,  
                             numMoved);  
    //多出来的最后一位删掉  
        elementData[--size] = null; // clear to let GC do its work  
  
        return oldValue;  
    }  
  
    //删除ArrayList中指定的元素  
    public boolean remove(Object o) {  
        if (o == null) {  
            for (int index = 0; index < size; index++)  
                if (elementData[index] == null) {  
                    fastRemove(index);  
                    return true;  
                }  
        } else {  
            for (int index = 0; index < size; index++)  
                if (o.equals(elementData[index])) {  
                    fastRemove(index);  
                    return true;  
                }  
        }  
        return false;  
    }  
  
    //private的快速删除与上面的public普通删除区别在于,没有进行边界判断以及不返回删除值  
    private void fastRemove(int index) {  
        modCount++;  
        int numMoved = size - index - 1;  
        if (numMoved > 0)  
            System.arraycopy(elementData, index+1, elementData, index,  
                             numMoved);  
        elementData[--size] = null; // clear to let GC do its work  
    }  
  
    //清空ArrayList,将全部元素置为null  
    public void clear() {  
        modCount++;  
  
        // clear to let GC do its work  
        for (int i = 0; i < size; i++)  
            elementData[i] = null;  
  
        size = 0;  
    }  
  
    //将集合C中所有的元素添加到ArrayList中  
    public boolean addAll(Collection c) {  
        Object[] a = c.toArray();  
        int numNew = a.length;  
        ensureCapacityInternal(size + numNew);  // Increments modCount  
    //在原来数组的后面添加c中所有的元素  
        System.arraycopy(a, 0, elementData, size, numNew);  
        size += numNew;  
        return numNew != 0;  
    }  
  
    //从index位置开始,将集合C中所欲的元素添加到ArrayList中  
    public boolean addAll(int index, Collection c) {  
        rangeCheckForAdd(index);  
  
        Object[] a = c.toArray();  
        int numNew = a.length;  
        ensureCapacityInternal(size + numNew);  // Increments modCount  
  
        int numMoved = size - index;  
        if (numMoved > 0)  
        //将index开始向后的所有数据,向后移动numNew个位置,给新插入的数据腾出空间  
            System.arraycopy(elementData, index, elementData, index + numNew,  
                             numMoved);  
    //将集合C中的数据插到刚刚腾出的位置  
        System.arraycopy(a, 0, elementData, index, numNew);  
        size += numNew;  
        return numNew != 0;  
    }  
  
    //删除从fromIndex到toIndex之间的数据,不包括toIndex位置的数据  
    protected void removeRange(int fromIndex, int toIndex) {  
        modCount++;  
        int numMoved = size - toIndex;  
        System.arraycopy(elementData, toIndex, elementData, fromIndex,  
                         numMoved);  
  
        // clear to let GC do its work  
        int newSize = size - (toIndex-fromIndex);  
        for (int i = newSize; i < size; i++) {  
            elementData[i] = null;  
        }  
        size = newSize;  
    }  
      
    //范围检测  
    private void rangeCheck(int index) {  
        if (index >= size)  
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));  
    }  
  
    //add和addAll方法中的范围检测  
    private void rangeCheckForAdd(int index) {  
        if (index > size || index < 0)  
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));  
    }  
  
    private String outOfBoundsMsg(int index) {  
        return "Index: "+index+", Size: "+size;  
    }  
  
    //删除ArrayList中所有集合C中包含的数据  
    public boolean removeAll(Collection c) {  
        return batchRemove(c, false);  
    }  
  
    //删除ArrayList中除了集合C中包含的数据外的其他所有数据  
    public boolean retainAll(Collection c) {  
        return batchRemove(c, true);  
    }  
      
    //批量删除  
    private boolean batchRemove(Collection c, boolean complement) {  
        final Object[] elementData = this.elementData;  
        int r = 0, w = 0;  
        boolean modified = false;  
        try {  
            for (; r < size; r++)  
                if (c.contains(elementData[r]) == complement)  
                    elementData[w++] = elementData[r];  
        } finally {  
            // Preserve behavioral compatibility with AbstractCollection,  
            // even if c.contains() throws.  
        //官方的注释是为了保持和AbstractCollection的兼容性  
        //我的理解是上面c.contains抛出了异常,导致for循环终止,那么必然会导致r != size  
        //所以0-w之间是需要保留的数据,同时从w索引开始将剩下没有循环的数据(也就是从r开始的)拷贝回来,也保留  
            if (r != size) {  
                System.arraycopy(elementData, r,  
                                 elementData, w,  
                                 size - r);  
                w += size - r;  
            }  
        //for循环完毕,检测了所有的元素  
        //0-w之间保存了需要留下的数据,w开始以及后面的数据全部清空  
            if (w != size) {  
                // clear to let GC do its work  
                for (int i = w; i < size; i++)  
                    elementData[i] = null;  
                modCount += size - w;  
                size = w;  
                modified = true;  
            }  
        }  
        return modified;  
    }  
  
/***************************** Writer and Read Object *************************/  
  
    //java.io.Serializable的写入函数  
    //将ArrayList的“容量、所有的元素值”都写入到输出流中  
    private void writeObject(java.io.ObjectOutputStream s)  
        throws java.io.IOException{  
        // Write out element count, and any hidden stuff  
        int expectedModCount = modCount;  
        s.defaultWriteObject();  
  
        // Write out size as capacity for behavioural compatibility with clone()  
    //写入“数组的容量”,保持与clone()的兼容性  
        s.writeInt(size);  
  
        //写入“数组的每一个元素”  
        for (int i=0; i

关于ArrayList有以下几点总结:####

  • 动态扩充容量
    ArrayList在每次增加元素(可能是1个,也可能是一组)时,都要调用该方法来确保足够的容量。当容量不足以容纳当前的元素个数时,就设置新的容量为旧的容量的1.5倍加1,如果设置后的新容量还不够,则直接新容量设置为传入的参数(也就是所需的容量),而后用Arrays.copyof()方法将元素拷贝到新的数组。从中可以看出,当容量不够时,每次增加元素,都要将原来的元素拷贝到一个新的数组中,非常之耗时,也因此建议在事先能确定元素数量的情况下,才使用ArrayList,否则建议使用LinkedList。

  • Arrays.copyOf()与System.copyOf()方法

    // Arrays.copyOf源码
    public static  T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }

    public static  T[] copyOf(U[] original, int newLength, Class newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            // 返回数组组件的类型
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        // 使用系统native函数,将数组复制到新数组中
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
  • ArrayList遍历访问的效率
// 基于迭代器遍历
Integer value = null;  
Iterator it = list.iterator();  
while (it.hasNext()) {  
    value = (Integer)it.next();  
}
// 基于随机访问遍历
Integer value = null;  
int size = list.size();  
for (int i = 0; i < size; i++) {  
    value = (Integer)list.get(i);          
}
// 基于增强for循环遍历
Integer value = null;  
for (Integer integ : list) {  
    value = integ;  
}

三种方式遍历,经过测试,基于随机访问(索引号的方式),遍历速度最快;ArrayList查找速度快,而插入和删除速度较慢;

  • ArrayList支持null类型
    在查找对象的索引号,移除指定的对象时,均进行null类型进行检查,可见ArrayList支持null类型;

你可能感兴趣的:(集合源码(一)| ArrayList源码剖析)