【Java8源码分析】集合框架-ArrayList

来源:互联网 发布:摄影网络销售技巧 编辑:程序博客网 时间:2024/05/29 07:42

一、总结

(1)ArrayList随机元素时间复杂度O(1),插入删除操作需大量移动元素,效率较低

(2)为了节约内存,当新建容器为空时,会共享Object[] EMPTY_ELEMENTDATA = {}Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}空数组

(3)容器底层采用数组存储,每次扩容为1.5倍

(4)ArrayList的实现中大量地调用了Arrays.copyof()System.arraycopy()方法,其实Arrays.copyof()内部也是调用System.arraycopy()System.arraycopy()为Native方法

(5)两个ToArray方法

  • Object[] toArray()方法。该方法有可能会抛出java.lang.ClassCastException异常
  • <T> T[] toArray(T[] a)方法。该方法可以直接将ArrayList转换得到的Array进行整体向下转型

(6)ArrayList可以存储null值

(7)ArrayList每次修改(增加、删除)容器时,都是修改自身的modCount;在生成迭代器时,迭代器会保存该modCount值,迭代器每次获取元素时,会比较自身的modCount与ArrayList的modCount是否相等,来判断容器是否已经被修改,如果被修改了则抛出异常(fast-fail机制)。

二、源码和注解

package java.util;public class ArrayList<E> extends AbstractList<E>        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{    private static final long serialVersionUID = 8683452581122892189L;    // 默认初始大小    private static final int DEFAULT_CAPACITY = 10;    // 指定大小的空的ArrayList共享此对象    private static final Object[] EMPTY_ELEMENTDATA = {};    // 默认大小的空的ArrayList共享    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};    // 存储容器,为数组    transient Object[] elementData;    // 存放容器大小    private int size;    // 传入初始大小    public ArrayList(int initialCapacity) {        if (initialCapacity > 0) {            this.elementData = new Object[initialCapacity];        } else if (initialCapacity == 0) {            this.elementData = EMPTY_ELEMENTDATA;        } else {            throw new IllegalArgumentException("Illegal Capacity: "+                                               initialCapacity);        }    }    // 无參构造    public ArrayList() {        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;    }    // 由Collection构造    public ArrayList(Collection<? extends E> c) {        elementData = c.toArray();        if ((size = elementData.length) != 0) {            if (elementData.getClass() != Object[].class)                elementData = Arrays.copyOf(elementData, size, Object[].class);        } else {            this.elementData = EMPTY_ELEMENTDATA;        }    }    // 将当前容量设为实际元素个数    public void trimToSize() {        modCount++;        if (size < elementData.length) {            elementData = (size == 0)              ? EMPTY_ELEMENTDATA              : Arrays.copyOf(elementData, size);        }    }    // 确保容器容量,当容器非空时,不得小于默认大小    public void ensureCapacity(int minCapacity) {        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)            ? 0            : DEFAULT_CAPACITY;        if (minCapacity > minExpand) {            ensureExplicitCapacity(minCapacity);        }    }    private void ensureCapacityInternal(int minCapacity) {        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);        }        ensureExplicitCapacity(minCapacity);    }    // 注意此方法在每次添加元素时调用,确保容量足够,且更改modCount    private void ensureExplicitCapacity(int minCapacity) {        modCount++;        if (minCapacity - elementData.length > 0)            grow(minCapacity);    }    // 数组最大元素个数,因为部分虚拟机会为数组预留了头部,故这里减8保证不会内存溢出    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;    // 扩容为minCapacity或者旧容器大小*1.5中较大的一个    private void grow(int minCapacity) {        int oldCapacity = elementData.length;        int newCapacity = oldCapacity + (oldCapacity >> 1);        if (newCapacity - minCapacity < 0)            newCapacity = minCapacity;        if (newCapacity - MAX_ARRAY_SIZE > 0)            newCapacity = hugeCapacity(minCapacity);        elementData = Arrays.copyOf(elementData, newCapacity);    }    private static int hugeCapacity(int minCapacity) {        if (minCapacity < 0) // 溢出            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;    }    // 遍历所有元素的方法,效率较低    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;    }    // 浅拷贝!!    public Object clone() {        try {            ArrayList<?> v = (ArrayList<?>) super.clone();            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(e);        }    }    // 该方法有可能会抛出java.lang.ClassCastException异常,    // 如果直接用向下转型的方法,将整个ArrayList集合转变为指定类型的Array数组,便会抛出该异常    public Object[] toArray() {        return Arrays.copyOf(elementData, size);    }    // 该方法可以直接将ArrayList转换得到的Array进行整体向下转型    @SuppressWarnings("unchecked")    public <T> T[] toArray(T[] a) {        if (a.length < size)            return (T[]) Arrays.copyOf(elementData, size, a.getClass());        System.arraycopy(elementData, 0, a, 0, size);        if (a.length > size)            a[size] = null;        return a;    }    @SuppressWarnings("unchecked")    E elementData(int index) {        return (E) elementData[index];    }    // 随机访问    public E get(int index) {        rangeCheck(index);        return elementData(index);    }    // 随机存储    public E set(int index, E element) {        rangeCheck(index);        E oldValue = elementData(index);        elementData[index] = element;        return oldValue;    }    // 末尾添加元素    public boolean add(E e) {        ensureCapacityInternal(size + 1);  // 改变modCount        elementData[size++] = e;        return true;    }    // 随机位置添加元素,需复制后续元素,效率较低    public void add(int index, E element) {        rangeCheckForAdd(index);        ensureCapacityInternal(size + 1);        // 复制插入位置的后续元素        System.arraycopy(elementData, index, elementData, index + 1,                         size - index);        elementData[index] = element;        size++;    }    public E remove(int index) {        rangeCheck(index);        modCount++;        E oldValue = elementData(index);        int numMoved = size - index - 1;        if (numMoved > 0)            System.arraycopy(elementData, index+1, elementData, index,                             numMoved);        // 设置不访问的元素为null,触发gc        elementData[--size] = null;        return oldValue;    }    // 删除第一个出现的元素    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 void fastRemove(int index) {        modCount++;        int numMoved = size - index - 1;        if (numMoved > 0)            System.arraycopy(elementData, index+1, elementData, index,                             numMoved);        elementData[--size] = null;    }    // 清楚所有元素,设置为null,但存储的elementData容量不变    public void clear() {        modCount++;        for (int i = 0; i < size; i++)            elementData[i] = null;        size = 0;    }    public boolean addAll(Collection<? extends E> c) {        Object[] a = c.toArray();        int numNew = a.length;        ensureCapacityInternal(size + numNew);  // Increments modCount        System.arraycopy(a, 0, elementData, size, numNew);        size += numNew;        return numNew != 0;    }    public boolean addAll(int index, Collection<? extends E> c) {        rangeCheckForAdd(index);        Object[] a = c.toArray();        int numNew = a.length;        ensureCapacityInternal(size + numNew);  // Increments modCount        int numMoved = size - index;        if (numMoved > 0)            System.arraycopy(elementData, index, elementData, index + numNew,                             numMoved);        System.arraycopy(a, 0, elementData, index, numNew);        size += numNew;        return numNew != 0;    }    protected void removeRange(int fromIndex, int toIndex) {        modCount++;        int numMoved = size - toIndex;        System.arraycopy(elementData, toIndex, elementData, fromIndex,                         numMoved);        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));    }    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;    }    public boolean removeAll(Collection<?> c) {        Objects.requireNonNull(c);        return batchRemove(c, false);    }    public boolean retainAll(Collection<?> c) {        Objects.requireNonNull(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.            if (r != size) {                System.arraycopy(elementData, r,                                 elementData, w,                                 size - r);                w += size - r;            }            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;    }    // 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()        s.writeInt(size);        // Write out all elements in the proper order.        for (int i=0; i<size; i++) {            s.writeObject(elementData[i]);        }        if (modCount != expectedModCount) {            throw new ConcurrentModificationException();        }    }    // java.io.Serializable的读取函数:根据写入方式读出        // 先将ArrayList的“容量”读出,然后将“所有的元素值”读出     private void readObject(java.io.ObjectInputStream s)        throws java.io.IOException, ClassNotFoundException {        elementData = EMPTY_ELEMENTDATA;        // Read in size, and any hidden stuff        s.defaultReadObject();        // Read in capacity        s.readInt(); // ignored        if (size > 0) {            // be like clone(), allocate array based upon size not capacity            ensureCapacityInternal(size);            Object[] a = elementData;            // Read in all elements in the proper order.            for (int i=0; i<size; i++) {                a[i] = s.readObject();            }        }    }}

三、参考

http://blog.csdn.net/ns_code/article/details/35568011

0 0
原创粉丝点击