ArrayList源码解析

一、ArrayList 属性

// 默认容量
private static final int DEFAULT_CAPACITY = 10;
// 一个空对象
private static final Object[] EMPTY_ELEMENTDATA = {};
// 一个空对象,无参默认创建
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 数据对象存放的地方,不参与序列化
transient Object[] elementData;// 1.transient 不参与序列化,思考:这个变量为什么不需要序列化?是可以通过计算得到?显然不是,那为什么这么设计呢?
// 实际的长度
private int size;
// 数组最大长度
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

二、构造函数

1.无参构造函数

public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

也就是说,此时的ArrayList 为空对象,创建出来的size为0

2.带int类型的构造参数

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

3.带Collection类型的构造参数

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底层就是Array数组

三、方法

1.add()方法

1.1 add(E e)

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!  // 1.1.1 ensureCapacityInternal 确认size+1之后不超过容量
        elementData[size++] = e;// 将elementData[size] = e; size自增
        return true;
    }

1.1.1 ensureCapacityInternal

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

private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//如果空数组,则返回(默认容量和数组+1之后的容量)的最大值,也就是这里会返回默认容量10
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
        }

private void ensureExplicitCapacity(int minCapacity) {
        modCount++; // abstractList protected transient int modCount = 0;   记录变更次数

        // overflow-conscious code
        if (minCapacity - elementData.length > 0) //容量>数组实际长度
            grow(minCapacity);
    }

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

第一次add时,elementData 长度变为10,然后一直可以添加,若添加到11个的时候,执行grow()方法, 将当前数组的长度变为原来容量的1.5倍,继续循环添加,

1.2 add(int index, E element)

public void add(int index, E element) {
        rangeCheckForAdd(index); //参数判断,若超出数组长度或者小于0则抛出IndexOutOfBoundsException

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);// index 之后的元素都往后移动1,包括index的元素
        elementData[index] = element;// 然后将index的元素赋值为插入的元素
        size++;
    }

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

2.remove

2.1 remove(int index)

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

此方法不缩减数组容量

将最后一个元素置为null,以便垃圾回收

返回被移除的元素

2.2 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;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work
}

若移除,返回true;若没有找到,返回false

 

 

 

参考文档:

https://blog.csdn.net/fighterandknight/article/details/61240861

 

 

 

 

 

 

 

 

 

 

 

 

 

 






posted on 2019-07-15 17:13  蜂巢巧克力面包  阅读(124)  评论(0编辑  收藏  举报