ArrayList源码分析

底层属性分析

	/**
     * Default initial capacity.
     * 当我们new一个空参构造器,然后第一次调用add方法时会扩容为10.
     */
    private static final int DEFAULT_CAPACITY = 10;
    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. 
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 存放元素的数组;补充:这说明ArrayList没法被序列化,可以使用工具kryo
     */
    transient Object[] elementData; 

    /**
     * The size of the ArrayList (the number of elements it contains).
     * 时刻保存当前列表的size
     * @serial
     */
    private int size;

构造方法分析

	/**
     * 方式1:当我们new一个空参构造器,是初始化为 DEFAULTCAPACITY_EMPTY_ELEMENTDATA(空数组)
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    /**
     * 方式2:初始化容量的构造方法
     * 分析:如果我们传入initialCapacity=0,是赋值另一个空数组EMPTY_ELEMENTDATA。
     * 这两个空数组会影响扩容的结果。
     * 
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity is negative
     */
    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);
        }
    }

add方法分析

	/**
     * 方式1:不指定插入位置,则会插入到list最后; 复杂度o(1)
     * 1.先检查是否需要扩容(检查当前的数组的length是不是大于等于minCapacity)
     * 2.让元素添加到数组的最后
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    /**
     * 计算minCapacity:add这个元素所需要的的最小容量
     * 1.如果我们是new的空参构造器,此时elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA,那么minCapacity=10
     * 2.其他情况都是size+1(一定要区分size和length)
     */
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
    /**
     * 判断最小容量是不是够,注意两件事:
     * 1.维护了一个modCount++;
     * 2.如果minCapacity大于当前数组length,调用grow方法扩容
     */
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
	/**
     * add方式2:复杂度o(n)
     * 1.基本结构和方式1相同
     * 2.确认容量之后,调用一个native方法,把index位置之后的元素都往后挪一位
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);

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

remove方法分析

	/**
     * remove方式1:
     * 1.需要传入index的方法,都会调用rangeCheck;如果index>=size,会抛出异常
     * 2.同样做了一个modeCount++
     * 3.调用native方法System.arraycopy移动元素
     */
    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;
    }
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
	/**
     * remove方式2:
     * 1.如果是null,会遍历一遍list中有没有null;注意是使用==判断
     * 2.如果不是null,同样会遍历一遍;通过equals方法,找到元素的index位置;
     * 3.如果没有找到,会返回false;
     */
    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;
    }
    /*
     * 和remove(int index)类似,只是不需要check index。
     * 同样维护了modCount++(这个参数和多线程有关,有点像乐观锁)
     */
    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
    }

扩容方法分析

	/**
     * 如果newCapacity大于minCapacity,扩容为newCapacity;否则扩容结果为minCapacity。
     *  
     * 1.可以看到,默认newCapacity是oldCapacity的1.5倍。(位运算往右移动一位,等效于/2)
     * 2.如果我们是new ArrayList(0),那么此时minCapcity=1,newCapacity=0;因此,此时newCapacity - minCapacity < 0,
     * 此时,newCapacity = minCapacity; 所以扩容结果是1.
     */
    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);
    }

多线程分析

**
 * 抛异常:java.util.ConcurrentModificationException(运行时异常)
 * 注意:只有调用迭代器的时候会抛出,才会检查modCount(比如打印时)
 */
public class JavaTest {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();

        for (int i = 0; i < 50; i++) {
            int finalI = i;
            new Thread(()-> {
                list.add(finalI);
            }).start();
            System.out.println(list);
        }
    }
}

	/**
     * 1.集合类中是重写了toString()方法的
     * 2.调用时,是通过迭代器;会调用next方法
     * 3.next方法如下:是ArrayList的内部类Itr中的方法
     */
    public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }

/**
 * 1.该内部类中维护了一个属性 int expectedModCount(类似于乐观锁中的版本号)
 * 2.next方法会调用,checkForComodification()
 * 3.如果modCount != expectedModCount(也就是中途有其他线程修改了List),那么抛出异常
 */
private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;   
        
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
        
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值