ArrayList源码解析

前提介绍:接口List

List<E> 接口
父接口Collection<E>
有序的Collection,也称序列。

ArrayList概述

父类关系
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.ArrayList<E>

实现接口
List<E>, 
RandomAccess, 
Cloneable, 
java.io.Serializable

非线性安全,底层数组,顺序储存结构,可存null。

成员变量

    // 序列化
    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 = {};
    // 这个数组就是ArrayList存储数据的地方它的长度就是数组的capacity。
    // 任何elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA的ArrayList,
    // 当第一个元素添加进来的时候,capacity自动增大为DEFAULT_CAPACITY
    transient Object[] elementData; 
    // List大小,也即当前数组中元素的数目
    private int size;

构造方法

// 指定容量的构造方法,大于0,实际储存数组为指定容量,等于0,使用EMPTY_ELEMENTDATA
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);
        }
    }
// 无参构造,直接使用默认静态空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA 
public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
// 长度大于0集合转换成Object数组后,实际储存数组,等于0,使用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;
        }
    }

成员方法

从几个代表方法中找出ArrayList容量可以扩增与缩减原理

boolean add(E e)

// 增加元素
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
// 扩大数组
private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
// 扩大数组
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // 判断扩大的minCapacity 是否大于数组实际储存(元素数量),如果大于,扩大数组容量
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

// 根据minCapacity的值,确定是否需要创建新数组
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        // 新数组容量为原数组的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        // 原数组大小扩展为1.5倍小于新数组,直接令新数组容量为所需扩展容量。
        // 因为add方法只可以加一个元素,进入此判断过程的
        // 个人理解是原列表为空或只有一个元素使时,即oldCapacity为0或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;
    }

void add(int index, E element)

// 指定位置添加元素
public void add(int index, E element) {
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // 数组copy
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
// 判断所传索引是否在List的size范围内  
private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

boolean remove(Object o)

(注意,只删除第一个符合条件的元素)

// 删除第一个元素
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;
        // 让索引位置元素位置后的元素依次向前进一步,设置最后一位为null,让Gc去缩减数组
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

E remove(int index)

// 删除索引位置元素
public E remove(int index) {
        rangeCheck(index);
        modCount++;
        E oldValue = elementData(index);
        int numMoved = size - index - 1;
        // 让索引位置元素位置后的元素依次向前进一步,设置最后一位为null,让Gc去缩减数组
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,numMoved);
        elementData[--size] = null; // clear to let GC do its work
        return oldValue;
    }
// 判断所传索引是否在List的size范围内 
private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

List subList(int fromIndex, int toIndex)

// 返回ArrayList的一部分
public List<E> subList(int fromIndex, int toIndex) {
        // 判断入参的合理性
        subListRangeCheck(fromIndex, toIndex, size);
        // 返回 Sublist对象
        return new SubList(this, 0, fromIndex, toIndex);
    }

    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > size)
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
    }

内部类SubList

private class SubList extends AbstractList<E> implements RandomAccess {
        // 成员变量
        private final AbstractList<E> parent;
        private final int parentOffset;
        private final int offset;
        int size;
        // 构造方法
        SubList(AbstractList<E> parent,
                int offset, int fromIndex, int toIndex) {
            this.parent = parent;
            this.parentOffset = fromIndex;
            this.offset = offset + fromIndex;
            this.size = toIndex - fromIndex;
            this.modCount = ArrayList.this.modCount;
        }
// 此类很多成员方法会更改AbstractList<E> parent,即原ArrayList
// set(),add(),remove(),removeRange(),addAll();好像查询遍历等都无影响,增删改都会改变ArrayList
}

modCount

一个继承父类AbstractList成员变量

// 列表结构上的修改次数
protected transient int modCount = 0;

总结

  • ArrayList默认初始化容量为10。
  • ArrayList在扩增时,如果数组总长度length < size + 1,复制为1.5倍。
  • ArrayList在缩减时(remove,clear等方法),会让相应位置为Null,等待Gc回收。
  • ArrayList线程不安全。
  • ArrayList中的subList方法生成的集合,集合更改会对原List产生影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值