ArrayList源码解析

本篇是源码解析系列文章的开篇,是基于JDK8分析的,之后的文章如没有特殊说明则JDK版本统一为8。
前言:因为最近换工作,面试较多,深深体会到面试官非常重视考察原理性的东西,而要对一个知识点的整体把握分析源码是一个很好的方式。

目录:
一. 概述
二. 源码分析
    (1) ArrayList初始化
    (2) ArrayList增加元素和扩容操作【增】
    (3) ArrayList的删除元素操作【删】
    (4) ArrayList的替换元素操作【改】
    (5) ArrayList的获取元素操作【查】
三. 与Vector的区别
四. 总结

一. 概述

(1)ArrayList是基于动态数组实现的,数组具有按索引查找的特性,所以访问很快,适合经常查询的数据;但每次插入或删除元素,就要大量地移动元素,插入删除元素的效率低。
(2) ArrayList 实现了RandomAccess, Cloneable, java.io.Serializable三个标记接口,表示它自身支持快速随机访问,克隆,序列化。

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


(3)ArrayList中允许元素为null。
(4)ArrayList是线程不安全的
5)默认情况下ArrayList容量为10,具备自动扩容机制,当容量不足时,会自动申请内存空间。扩容操作是比较消耗性能的,如果在初始化的时候知道数据的大小,可以通过指定参数的构造器去构建实例 ,以减少扩容次数提高效率。

二. 源码分析

(1ArrayList初始化

我们先来看下重要的几个的全局变量。

    /**
     * 默认初始化数组大小
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 用于空实例的共享空数组实例
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 用于默认大小的空实例的共享空数组实例。用于区别上面的EMPTY_ELEMENTDATA
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     *存储ArrayList元素的数组缓冲区
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * ArrayList当前放了多少个元素
     */
    private int size;

elementData属性采用了transient来修饰,表明其不使用Java默认的序列化机制来实例化,因为ArrayList自己实现了序列化和反序列化的方法。

构造器

    /**
     * 指定参数构造器
     */
    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);
        }
    }

    /**
     * 无参构造器,构造一个默认大小为10的空列表
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    
/**
 * 构造一个包含指定集合元素的列表,元素的顺序由集合的迭代器返回。
 */
 public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    if ((size = elementData.length) != 0) {
        // c.toArray 可能(错误地)不返回 Object[]类型的数组(参见JDK Bug 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        // 如果集合大小为空将赋值为 EMPTY_ELEMENTDATA 
        this.elementData = EMPTY_ELEMENTDATA;
    }
 }  

(2ArrayList增加元素和扩容操作【增】

 1.添加单个元素到数组末尾,add(E e)方法

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;//从数组末尾添加一个元素,并新增size
        return true;
 }

private static int calculateCapacity(Object[] elementData, int minCapacity) {
        //如果是默认构造函数构建的数组,返回默认初始大小和当前值的最大值,否则返回当前值
        //从这里可以看出使用默认构造函数初始化是在第一次add时才构建数组大小的
        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次数
        modCount++;

        // overflow-conscious code
        //add后的最小容量大小>当前数组的容量时就需要扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
 }

private void grow(int minCapacity) {
        //1.旧的数组大小
        int oldCapacity = elementData.length;
        //2.默认扩容一半
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //3.如果新的数组容量比add后的最小容量还小的话,就扩容为add后的最小容量大小
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //4.判断新的数组容量如果超过最的数组大小(Intenger.MAX_VALUE-8)则创建一个巨大容量的数组
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        //5.复制数组
        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;
  }

 2.添加单个元素到指定位置,add(int index, E element)方法

public void add(int index, E element) {
        //检查索引有效性
        rangeCheckForAdd(index);
        //是否需要扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //在index后的元素向后移动一位
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //将新元素插入到原来index位置
        elementData[index] = element;
        //元素个数+1
        size++;
}

3.添加集合到数组末尾,addAll(Collection<? Extends E>   c)方法

 public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        //是否需要扩容
        ensureCapacityInternal(size + numNew);  // Increments modCount
        //将a数组全部复制到末尾
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
}

4.添加集合到指定位置,addAll(int index,Collection<? Extends E>   c)方法

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)//如果后面没有元素就相当于插入末尾
            //将需要的移动的元素往后移动numNew位
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
        //复制数组a到指定位置
        System.arraycopy(a, 0, elementData, index, numNew);
        //元素个数增加numNew个
        size += numNew;
        return numNew != 0;
}

(3ArrayList的删除元素操作【删】

1.移除指定位置的元素,remove(int index)方法

public E remove(int index) {
        //1.校验索引有效性
        rangeCheck(index);

        modCount++;
        //获取到指定元素
        E oldValue = elementData(index);
        //需要往前移1位的元素个数
        int numMoved = size - index - 1;
        if (numMoved > 0)
            //将index(不包含)后面的元素往前移动1位
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //先是size-1,然后最后个元素置空
        elementData[--size] = null; // clear to let GC do its work
        //返回index位置的旧值
        return oldValue;
 }

 private void rangeCheck(int index) {
        //如果index大于或等于size,则抛出下标异常
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 }

2.移除指定的元素,remove(Object o)方法

public boolean remove(Object o) {
        //判断是否为null
        if (o == null) {
            //遍历移除第一个为null的元素
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            //遍历移除第一个为o的元素
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

3.移除指定区间位置的元素,removeRange(int fromIndex,int toIndex)方法

protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        //1.需要往前移动的元素个数
        int numMoved = size - toIndex;
        //2.将toIndex后面的元素复制到fromIndex处
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        //计算新的元素个数
        int newSize = size - (toIndex-fromIndex);
        //4.将后面的元素置空
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
}

4.移除指定集合里的所有元素,removeAll(Collection<? Extends E>   c)方法

public boolean removeAll(Collection<?> c) {
        //判断集合是否为空,若为空则抛出空指针异常
        Objects.requireNonNull(c);
        return batchRemove(c, false);
}

//批量移动
//complement是true 则移除elementData中除了c以外的其他元素
//complement是false 则移除c和elementData都含有的元素
private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;//w 代表批量删除后 数组还剩多少元素
    boolean modified = false;
    try {
        //高效的保存两个集合公有元素的算法
        for (; r < size; r++)
            if (c.contains(elementData[r]) == complement) // 如果 c里不包含当前下标元素, 
                elementData[w++] = elementData[r];//则保留
    } finally {
        if (r != size) { //出现异常会导致 r !=size , 则将出现异常处后面的数据全部复制覆盖到数组里。
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;//修改 w数量
        }
        if (w != size) {//置空数组后面的元素
            // clear to let GC do its work
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;//修改modCount
            size = w;// 修改size
            modified = true;
        }
    }
    return modified;
}

5.清空集合,clear()方法

public void clear() {
        modCount++;

        // clear to let GC do its work
        //遍历集合,把每个元素置为空,由GC回收
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
 }

(4ArrayList的替换元素操作【改】

1.替换指定位置的元素,set(int index, E element)方法

public E set(int index, E element) {
        rangeCheck(index);//检查索引有效性

        E oldValue = elementData(index);//获取到旧值
        elementData[index] = element;//将该位置替换为新值
        return oldValue;//返回旧值
    }

(5ArrayList的获取元素操作【查】
获取元素操作大致归纳为获取元素,遍历集合,判断集合是否包含某个元素。

1.获取指定位置的元素,get(int index)方法

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];//获取指定位置的元素
    }

    public E get(int index) {
        rangeCheck(index);//检查索引有效性

        return elementData(index);
    }

2.遍历集合,Iterator()方法

public Iterator<E> iterator() {
        return new Itr();
}

private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return //默认是0
    int lastRet = -1; // index of last element returned; -1 if no such  //上一次返回的元素 (删除的标志位)
    int expectedModCount = modCount; //用于判断集合是否修改过结构的 标志

    public boolean hasNext() {
        return cursor != size;//游标是否移动至尾部
    }

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)//判断是否越界
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)//再次判断是否越界,在我们这里的操作时,有异步线程修改了List
            throw new ConcurrentModificationException();
        cursor = i + 1;//游标+1
        return (E) elementData[lastRet = i];//返回元素 ,并设置上一次返回的元素的下标
    }

    public void remove() {//remove 掉 上一次next的元素
        if (lastRet < 0)//先判断是否next过
            throw new IllegalStateException();
        checkForComodification();//判断是否修改过

        try {
            ArrayList.this.remove(lastRet);//删除元素 remove方法内会修改 modCount 所以后面要更新Iterator里的这个标志值
            cursor = lastRet; //要删除的游标
            lastRet = -1; //不能重复删除 所以修改删除的标志位
            expectedModCount = modCount;//更新 判断集合是否修改的标志,
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }
//判断是否修改过了List的结构,如果有修改,抛出异常
    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

3.判断集合是否含有某个元素,contains(Object o)方法

    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    public int indexOf(Object o) {
        if (o == null) {
            //如果元素为空,则返回第一个null的索引
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            //如果元素不为空,则返回第一个o的索引
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;//没找到,则返回-1
    }

三. 与Vector的区别

ArrayList与Vector 基本是一致的,都是 基于动态数组 实现的,允许元素为null,都有 扩容机制
不同点:

(1)Vector是线程安全的,会在可能出现线程安全的方法前面加上synchronized关键字。
2)在构造方法方面, Vector ArrayList多了一个方法,在这个方法中可以新传入了一个叫capacityIncrement的参数,用于自定义扩容。

//Vector构造器
public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }
3)两者的扩容方案不同
//Vector扩容
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
}

ArrayList中,扩容的时候一般都是增加0.5倍左右,而在 Vector中,如果在构造方法中指定了capacityIncrement的值,就会在原来容量的基础上线性增加capacityIncrement,如果没有指定这个参数,则默认增加一倍容量(如果新容量还不够,则直接设置新容量为所需的容量),而后同样用Arrays.copyof()方法将元素拷贝到新的数组。

 4Vector已经被废弃掉

四. 总结

(1)这是个人的第一篇技术博客,无论写的好不好都要试着去尝试,并且要有自己的思路,前提是要动起手来,光看是远远不够的,希望这是个好的开始。


参考资料:
https://blog.csdn.net/xfhy_/article/details/80193648
https://blog.csdn.net/seu_calvin/article/details/52742373
https://blog.csdn.net/zxt0601/article/details/77281231
https://www.cnblogs.com/gxl1995/p/7534171344218b3784f1beb90d621337.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值