ArrayList源码深入分析

来源:http://www.sh-fengwen.com 作者:美高梅游戏平台网站 人气:185 发布时间:2019-09-07
摘要:/*** ArrayList is an implementation of {@linkList}, backed by an array.* All optional operations including adding, removing, and replacing elements are supported.**All elements are permitted, including null.**This class is a good choice as
/*** ArrayList is an implementation of {@linkList}, backed by an array.* All optional operations including adding, removing, and replacing elements are supported.**All elements are permitted, including null.**This class is a good choice as your default {@codeList} implementation.* {@linkVector} synchronizes all operations, but not necessarily in a way that's* meaningful to your application: synchronizing each call to {@codeget}, for example, is not* equivalent to synchronizing the list and iterating over it (which is probably what you intended).* {@linkjava.util.concurrent.CopyOnWriteArrayList} is intended for the special case of very high* concurrency, frequent traversals, and very rare mutations.**@paramThe element type of this list.*@since1.2*/

电子游戏美高梅网址,以下资料整理自互联网,仅用于个人学习

以上是ArrayList的类前注释。大致意思如下:ArrayList是底层用数组实现的List。支持增删改等操作。支持包括null的任意类型元素。Vector使用synchronized来进行线程同步;CopyOnWriteArrayList适合确保高并发场景下的线程安全;在一般情况下使用ArrayList效率较高。


下面从代码里的几个主要属性和方法入手。

美高梅游戏平台网站,ArrayList简介

ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长。

ArrayList不是线程安全的,多线程情况下可以考虑用collections.synchronizedList(List l)函数返回一个线程安全的ArrayList类,也可以使用concurrent并发包下的CopyOnWriteArrayList类。

ArrayList实现了Serializable接口,因此它支持序列化。实现了RandomAccess接口,支持快速随机访问,实际上就是通过下标快速访问。实现了Cloneable接口,能进行克隆。


 /** * The minimum amount by which the capacity of an ArrayList will increase. * This tuning parameter controls a time-space tradeoff. This value  * gives empirically good results and is arguably consistent with the * RI's specified default initial capacity of 10: instead of 10, we start * with 0 (sans allocation) and jump to 12. */ private static final int MIN_CAPACITY_INCREMENT = 12;

源码分析

package java.util;    

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

    // ArrayList基于该数组实现,用该数组保存数据   
    private transient Object[] elementData;    

    // ArrayList中实际数据的数量    
    private int size;    

    // ArrayList带容量大小的构造函数。    
    public ArrayList(int initialCapacity) {    
        super();    
        if (initialCapacity < 0)    
            throw new IllegalArgumentException("Illegal Capacity: "+    
                                               initialCapacity);    
        // 新建一个数组    
        this.elementData = new Object[initialCapacity];    
    }    

    // ArrayList无参构造函数。默认容量是10。    
    public ArrayList() {    
        this(10);    
    }    

    // 创建一个包含collection的ArrayList    
    public ArrayList(Collection<? extends E> c) {    
        elementData = c.toArray();    
        size = elementData.length;    
        if (elementData.getClass() != Object[].class)    
            elementData = Arrays.copyOf(elementData, size, Object[].class);    
    }    


    // 将当前容量值设为实际元素个数    
    public void trimToSize() {    
        modCount++;    
        int oldCapacity = elementData.length;    
        if (size < oldCapacity) {    
            elementData = Arrays.copyOf(elementData, size);    
        }    
    }    


    // 确定ArrarList的容量。    
    public void ensureCapacity(int minCapacity) {    
        // 将“修改统计数”+1,该变量主要是用来实现fail-fast机制的    
        modCount++;    
        int oldCapacity = elementData.length;    
        // 若当前容量不足以容纳当前的元素个数,设置 新的容量=“(原始容量x3)/2 + 1”    
        if (minCapacity > oldCapacity) {    
            Object oldData[] = elementData;    
            int newCapacity = (oldCapacity * 3)/2 + 1;    
            //如果还不够,则直接将minCapacity设置为当前容量  
            if (newCapacity < minCapacity)    
                newCapacity = minCapacity;    
            elementData = Arrays.copyOf(elementData, newCapacity);    
        }    
    }    

    // 返回ArrayList的实际大小    
    public int size() {    
        return size;    
    }    

    // ArrayList是否包含Object(o)    
    public boolean contains(Object o) {    
        return indexOf(o) >= 0;    
    }    

    //返回ArrayList是否为空    
    public boolean isEmpty() {    
        return size == 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;    
        }      
    }    

    // 反向查找(从数组末尾向开始查找),返回元素(o)的索引值    
    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;    
    }    


    // 返回ArrayList的Object数组    
    public Object[] toArray() {    
        return Arrays.copyOf(elementData, size);    
    }    

    // 返回ArrayList元素组成的数组  
    public <T> 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;    
    }    

    // 获取index位置的元素值    
    public E get(int index) {    
        RangeCheck(index);    

        return (E) elementData[index];    
    }    

    // 设置index位置的值为element    
    public E set(int index, E element) {    
        RangeCheck(index);    

        E oldValue = (E) elementData[index];    
        elementData[index] = element;    
        return oldValue;    
    }    

    // 添加元素e    
    public boolean add(E e) {    
        // 确定ArrayList的容量大小    
        ensureCapacity(size + 1);  // Increments modCount!!    
        // 添加e到ArrayList中    
        elementData[size++] = e;    
        return true;    
    }  

    // 将e添加到ArrayList的指定位置    
    public void add(int index, E element) {    
        if (index > size || index < 0)    
            throw new IndexOutOfBoundsException(    
            "Index: "+index+", Size: "+size);    

        ensureCapacity(size+1);  // Increments modCount!!    
        System.arraycopy(elementData, index, elementData, index + 1,    
             size - index);    
        elementData[index] = element;    
        size++;    
    }    

    // 删除ArrayList指定位置的元素    
    public E remove(int index) {    
        RangeCheck(index);    

        modCount++;    
        E oldValue = (E) elementData[index];    
        // 从"index+1"开始,用后面的元素替换前面的元素。
        int numMoved = size - index - 1;    
        if (numMoved > 0)    
            System.arraycopy(elementData, index+1, elementData, index,    
                 numMoved);    
        elementData[--size] = null; // 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;    
    }    


    // 快速删除第index个元素    
    private void fastRemove(int index) {    
        modCount++;    
        int numMoved = size - index - 1;    
        // 从"index+1"开始,用后面的元素替换前面的元素。    
        if (numMoved > 0)    
            System.arraycopy(elementData, index+1, elementData, index,    
                             numMoved);    
        // 将最后一个元素设为null    
        elementData[--size] = null; // Let gc do its work    
    }    

    // 清空ArrayList,将全部的元素设为null    
    public void clear() {    
        modCount++;    

        for (int i = 0; i < size; i++)    
            elementData[i] = null;    

        size = 0;    
    }    

    // 将集合c追加到ArrayList中    
    public boolean addAll(Collection<? extends E> c) {    
        Object[] a = c.toArray();    
        int numNew = a.length;    
        ensureCapacity(size + numNew);  // Increments modCount    
        System.arraycopy(a, 0, elementData, size, numNew);    
        size += numNew;    
        return numNew != 0;    
    }    

    // 从index位置开始,将集合c添加到ArrayList    
    public boolean addAll(int index, Collection<? extends E> c) {    
        if (index > size || index < 0)    
            throw new IndexOutOfBoundsException(    
            "Index: " + index + ", Size: " + size);    

        Object[] a = c.toArray();    
        int numNew = a.length;    
        ensureCapacity(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;    
    }    

    // 删除fromIndex到toIndex之间的全部元素。    
    protected void removeRange(int fromIndex, int toIndex) {    
    modCount++;    
    int numMoved = size - toIndex;    
        System.arraycopy(elementData, toIndex, elementData, fromIndex,    
                         numMoved);    

    // Let gc do its work    
    int newSize = size - (toIndex-fromIndex);    
    while (size != newSize)    
        elementData[--size] = null;    
    }    

    private void RangeCheck(int index) {    
    if (index >= size)    
        throw new IndexOutOfBoundsException(    
        "Index: "+index+", Size: "+size);    
    }    


    // 克隆函数    
    public Object clone() {    
        try {    
            ArrayList<E> v = (ArrayList<E>) 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();    
        }    
    }    


    // 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();    

        // 写入“数组的容量”    
        s.writeInt(elementData.length);    

    // 写入“数组的每一个元素”    
    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 {    
        // Read in size, and any hidden stuff    
        s.defaultReadObject();    

        // 从输入流中读取ArrayList的“容量”    
        int arrayLength = s.readInt();    
        Object[] a = elementData = new Object[arrayLength];    

        // 从输入流中将“所有的元素值”读出    
        for (int i=0; i<size; i++)    
            a[i] = s.readObject();    
    }    
}  

与JDK源码不同,JDK初始容量是10,而Android下是初始0再跳到12。不不不你说12好一般人也看不出妙在哪啊难道是8派和16派僵持不下最后折中成12吗。

总结

  • ArrayList有三个不同的构造方法,无参构造方法的容量默认为10,带指定容量的构造方法,带Collection参数的构造方法将Collection转化为数组赋值给ArrayList中的实现数组。

  • ensureCapacity方法,每次添加元素时都要调用该方法来确保足够的容量,当容量不足以容纳当前的元素个数时,就设置新的容量为旧的容量的1.5倍加1,如果设置后的新容量还不够,则直接新容量设置为传入的参数(也就是所需的容量),然后用Arrays.copyof()方法将元素拷贝到新的数组。

  • ArrayList在容量不足时添加元素,都会进行数组的拷贝,所以会非常耗时,因此建议在事先知道元素个数的情况下使用ArrayList,否则建议使用LinkedList。

  • ArrayList基于数组实现,可通过下标直接查找,所以查找效率高,添加删除元素时要移动大量元素,所以添加删除元素效率低。

  • ArrayList允许元素为null。

 /** * The elements in this list, followed by nulls. */ transient Object[] array;

Object数组array用来存储元素。值得注意的是修饰符transient。transient的作用是使可序列化对象中的指定属性不被序列化。而在这里使用transient的目的,是因为直接序列化array的话array里可能存在一定数量的空值导致浪费资源。

 /** * Adds the specified object at the end of this {@code ArrayList}. * * @param object * the object to add. * @return always true */ @Override public boolean add { Object[] a = array; int s = size; if (s == a.length) { Object[] newArray = new Object[s + (s < (MIN_CAPACITY_INCREMENT / 2) ? MIN_CAPACITY_INCREMENT : s >> 1)]; System.arraycopy(a, 0, newArray, 0, s); array = a = newArray; } a[s] = object; size = s + 1; modCount++; return true; } /** * Inserts the specified object into this {@code ArrayList} at the specified * location. The object is inserted before any previous element at the * specified location. If the location is equal to the size of this * {@code ArrayList}, the object is added at the end. * * @param index * the index at which to insert the object. * @param object * the object to add. * @throws IndexOutOfBoundsException * when {@code location < 0 || location > size()} */ @Override public void add(int index, E object) { Object[] a = array; int s = size; if (index > s || index < 0) { throwIndexOutOfBoundsException; } if (s < a.length) { System.arraycopy(a, index, a, index + 1, s - index); } else { // assert s == a.length; Object[] newArray = new Object[newCapacity]; System.arraycopy(a, 0, newArray, 0, index); System.arraycopy(a, index, newArray, index + 1, s - index); array = a = newArray; } a[index] = object; size = s + 1; modCount++; } /** * This method controls the growth of ArrayList capacities. It represents * a time-space tradeoff: we don't want to grow lists too frequently * (which wastes time and fragments storage), but we don't want to waste * too much space in unused excess capacity. * * NOTE: This method is inlined into {@link #add} for performance. * If you change the method, change it there too! */ private static int newCapacity(int currentCapacity) { int increment = (currentCapacity < (MIN_CAPACITY_INCREMENT / 2) ? MIN_CAPACITY_INCREMENT : currentCapacity >> 1); return currentCapacity + increment; }

增。如果数组已满则进行扩容。扩容方式为:若容量小于6则增加12,否则1.5倍扩容。

 /** * Adds the objects in the specified collection to this {@code ArrayList}. * * @param collection * the collection of objects. * @return {@code true} if this {@code ArrayList} is modified, {@code false} * otherwise. */ @Override public boolean addAll(Collection<? extends E> collection) { Object[] newPart = collection.toArray(); int newPartSize = newPart.length; if (newPartSize == 0) { return false; } Object[] a = array; int s = size; int newSize = s + newPartSize; // If add overflows, arraycopy will fail if (newSize > a.length) { int newCapacity = newCapacity(newSize - 1); // ~33% growth room Object[] newArray = new Object[newCapacity]; System.arraycopy(a, 0, newArray, 0, s); array = a = newArray; } System.arraycopy(newPart, 0, a, s, newPartSize); size = newSize; modCount++; return true; }

批量增。又与JDK实现不同:JDK是扩容为新容量与1.5倍容量的较大者;此处为 以新容量为基准1.5倍扩容。如newCapacity方法的注释所写:这是时间空间权衡,既不想频繁扩容,又不想浪费过多冗余空间。就这种扩容方式而言,容量比JDK的方式要大,减少了扩容次数,想必思路倾向于以空间换时间。

本文由美高梅游戏平台网站发布于美高梅游戏平台网站,转载请注明出处:ArrayList源码深入分析

关键词:

最火资讯