Java源码阅读ArrayList

Posted OUYM

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java源码阅读ArrayList相关的知识,希望对你有一定的参考价值。

1简介

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

ArrayList使用一个可变数组实现List接口,实现了List接口的所有可选操作。ArrayList除了是非线程安全的之外,其他的与Vector类似。

2成员属性

//序列化版本号    
private static final long serialVersionUID = 8683452581122892189L;

//默认容量
private static final int DEFAULT_CAPACITY = 10;

//默认数组,没有元素,空数组
private static final Object[] EMPTY_ELEMENTDATA = {};

//默认容量数组
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

//存放元素的数组
transient Object[] elementData; 

//当前ArrayList里面元素存放数量   
private int size;

3构造函数

 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;
    }

    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

上面几个构造函数没什么好讲的,但有一个疑问,正常来说DEFAULTCAPACITY_EMPTY_ELEMENTDATA容量应该为10,可是我们在属性的里声明的时候却是为空的,为什么会这样?不急,接下来的扩容代码给出了很好的解释。与Vector一样,ArrayList可以调用trimToSize将多余的空间释放,也可以扩充容量。

4可收缩容量

(1)trimToSize方法

 

 public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

 

size属性是集合里现有元素的个数,elementData.length是数组的实际长度。我们可以trimToSize将数组标号为[size,elementData.length-1]的空间释放。

(2)扩容

public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // any size if not default element table
            ? 0
            // larger than default for default empty table. It‘s already
            // supposed to be at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        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;
    }

我们先解释一下DEFAULTCAPACITY_EMPTY_ELEMENTDATA容量问题:

当调用add方法添加元素时,首先会执行ensureCapacityInternal(size + 1),进入该方法后只有一条ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)),当elementData是DEFAULTCAPACITY_EMPTY_ELEMENTDATA时,calculateCapacity方法会返回DEFAULT_CAPACITY和size + 1的较大值。size默认从0开始的,所以第一次调用add方法时且当elementData是DEFAULTCAPACITY_EMPTY_ELEMENTDATA时,就会对进行扩容操作,而扩容的容量正好是DEFAULT_CAPACITY(10)。

然后我们分析手动调用ensureCapacity(minCapacity)进行扩容的过程:

进入该方法后,第一步是求minExpand,这里会判读实际数组是否等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA,若是的话minExpand赋值为DEFAULT_CAPACITY(10),否则为0。然后确保参数minCapacity大于minExpand,才进行后续的扩容操作,调用ensureExplicitCapacity(minCapacity)。

ensureExplicitCapacity方法确保minCapacity大于当前容量elementData.length才进行扩容操作,调用 grow(minCapacity)。

因为扩容原理是复制数组,这是个是个很费计算机资源的操作,应该尽量减少扩容次数,所以每次扩容都会保证最小扩容(旧容量*1.5),grow方法的主要功能就是这个。

5查找

 

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 E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }
     //set放着一起看吧
     public E set(int index, E element) {
        rangeCheck(index);

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

      private void rangeCheck(int index) {
            if (index >= size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
      }

查找的时候注意判断null,因为null.equals()是会报空指针异常的。indexOf是从前往后遍历数组,lastIndexOf则是从后往前遍历。

6集合基本操作

(1)添加元素

//在末尾添加一个元素
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // 检查是否需要扩容
        elementData[size++] = e;
        return true;
    }

//在指定位置添加一个元素
 public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,size - index); // index后的所有元素均后移一位
        elementData[index] = element;
        size++;
    }

//添加一堆元素
 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;
    }

private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

(2)删除元素

//删除指定位置的元素
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);
        elementData[--size] = null; // clear to let GC do its work

        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; // clear to let GC do its work
    }

//删除索引为[fromIndex,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;
    }

//删除一堆元素
public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c); //检查集合c不能为空,否则报空指针异常
        return batchRemove(c, false);
    }

 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;
    }

//清空(删除所有元素)
public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

remove和fastRemove的区别是后者没有范围检查,只有确定不会越界的情况下才会调用fastRemove来提升效率。

值得注意的是与Vector不同,这里删除一堆元素不是通过迭代器实现的,而是通过batchRemove方法,该批量删除方法会遍历数据数组。当complement参数为false时,把不属于参数集合里的元素替换到原数组里面。为true时,把原集合中属于参数集合里的元素替换到原数组里面。

未完....

 

以上是关于Java源码阅读ArrayList的主要内容,如果未能解决你的问题,请参考以下文章

java8 ArrayList源码阅读

Java源码阅读ArrayList

JDK源码阅读:ArrayList源码解析

jdk源码阅读笔记之java集合框架(ArrayList)

JAVA 集合类(java.util)源码阅读笔记------ArrayList

JDK1.8-java.util.ArrayList类源码阅读