ArrayList分析

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;        //arraylist的元素个数

其中的EMPTY_ELEMENTDATA 和DEFAULTCAPACITY_EMPTY_ELEMENTDATA 为两个空数组,区别是DEFAULTCAPACITY_EMPTY_ELEMENTDATA 是当构造空的数组的使用,并且当第一个元素加进来的时候这个数组是知道怎么扩容的,结合下边的构造函数和新增元素add方法区分

构造方法

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

这个构造方法给了一个初始大小,可以看到初始化的时候this.elementData = EMPTY_ELEMENTDATA; 实用的是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;
        }
    }

这个构造方法传入一个数组,初始化的时候用得EMPTY_ELEMENTDATA
构造方法

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

这个构造方法是什么都没传,初始化的时候用得DEFAULTCAPACITY_EMPTY_ELEMENTDATA

add新增元素

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // 扩容机制
        elementData[size++] = e;   //直接往后加元素
        return true;
    }

扩容

private void ensureCapacityInternal(int minCapacity) {
        //如果数组等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA,也就是第一次新增元素,minCapacity 取DEFAULT_CAPACITY和minCapacity里的最大值,minCapacity为数组当前大小size再加上1;size+1
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;//修改计数器,为了实现fail-fast机制,可以理解为维护数组数据的一致性,没修改一次数组计数器+1,如果在多线程环境下,两个线程都修改数组,这个数组的modCount对不上,就会抛出异常

        // overflow-conscious code
        //当是第一次新增时minCapacity 取得是elementData.length+1和DEFAULT_CAPACITY的较大值,所以为true,如果不是第一次新增,minCapacity = size + 1,此处用来判断是否需要扩容复制原数组,如果需要的长度minCapacity > 数组长度,则扩容,否则不扩容(比如传入空初始化,size是10,假如9个元素之后,这时候新加一个元素,所需长度是10,数组大小是10,不大于0,需要扩容,size每次新增元素都会+1)
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;     //原数组大小size
        int newCapacity = oldCapacity + (oldCapacity >> 1);   //新的size为原数组大小的1.5倍
        if (newCapacity - minCapacity < 0) //如果newCapacity < minCapacity 
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)  //如果newCapacity > MAX_ARRAY_SIZE 
            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;
    }

Arrays.copyOf方法出入数组和size

@SuppressWarnings("unchecked")
    public static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }

copyOf方法,传入数组,大小和类型

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        //判断数组的类型,创建实例
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

System.arraycopy方法对新实例赋值在返回

指定位置新增

public void add(int index, E element) {
        rangeCheckForAdd(index);   //检查index是否超出范围

        ensureCapacityInternal(size + 1);  // Increments modCount!! 检查是否需要扩容
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);//调用原生方法,复制数组元素,将elementData数组中从index开始长度为size - index的元素(其实就是index以后的所有元素)复制到elementData数组的index+1的位置,其实就是把数组元素index之后元素往后移动一位
        elementData[index] = element;// 插入元素在index
        size++;// 长度+1
    }

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

//src:原数组
//srcPos:原数组中的开始位置
//dest:目标数组
//destPos:目标数组中的开始位置
//length:被复制的数组元素长度
public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

传入数组新增

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

其他方法

//判断数组是否为空
public boolean isEmpty() {
        return size == 0;
    }
//返回数组大小,数组大小在每次add的时候都会改变size的值
public int size() {
        return size;
    }

判断是否包含某元素

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

正向查找

public int indexOf(Object o) {
        if (o == null) { //o==null
            for (int i = 0; i < size; i++)//循环整个数组
                if (elementData[i]==null)  //是否有等于null的元素
                    return i;//有就返回元素位置
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i])) //比较值是否相等
                    return i;
        }
        return -1;//没找到就返回-1
    }

从这段代码可以看出,arrayList的元素可以为空
反向查找

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 Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;//新数组的计数器置0
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

转化成普通数组

public Object[] toArray() {
        return Arrays.copyOf(elementData, size);//在不指定第三个参数的情况下Arrays.copyOf()的第一个参数的类型就是要转化成的类型,见上 
    }

get()方法

    public E get(int index) {//E是arrayList声明时的泛型
        rangeCheck(index);//检查index是否超出范围
        return elementData(index);//返回指定位置元素
    }
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];//arrayList是基于数组的,返回指定位置元素
    }

set()方法

 public E set(int index, E element) {
        rangeCheck(index);//检查index是否超出范围
        E oldValue = elementData(index);//获取指定位置元素
        elementData[index] = element;//重新赋值
        return oldValue;//返回原来的被替换的值
    }

删除

public boolean remove(Object o) {
        if (o == null) {//正向查找,可以为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++;//计数器+1
        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置null,让GC回收
    }

public E remove(int index) {
        rangeCheck(index);    //检查index合法性
        modCount++;           //每次修改数组,计数器+1,防止多线程环境下数据不一致
        E oldValue = elementData(index);           //找到对应位置的元素
        int numMoved = size - index - 1;           //计算需要移动的元素个数
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);//移动元素,实际就是复制index+1以后的元素到index
        elementData[--size] = null; // clear to let GC do its work设置成null,让GC回收
        return oldValue;
    }

清空数组

public void clear() {
        modCount++;//计数器+1
        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;//循环将所有元素置null
        size = 0;//设置数组大小为0
    }

指定范围删除

protected void removeRange(int fromIndex, int toIndex) {
        modCount++;//计数器+1
        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);
    }

public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

private boolean batchRemove(Collection<?> c, boolean complement) {//removeAll删除时传入的complement为false
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)//循环整个elementData数组
                if (c.contains(elementData[r]) == complement)//如果c不包含elementData的元素,就给elementData重新赋值,包含的元素舍弃
                    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) {//删除元素成功后,将多余的位置置null,等待GC回收
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;//对size重新赋值
                modified = true;
            }
        }
        return modified;
    }

保留指定的数组元素

public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);//检查c是否为空
        return batchRemove(c, true);
    }

private boolean batchRemove(Collection<?> c, boolean complement) {//保留元素时complement为true
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)//如果c包含elementData元素,重新对elementData赋值,包含的保留,可以对比removeAll()看
                    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;
    }

排序

@Override
    @SuppressWarnings("unchecked")
    public void sort(Comparator<? super E> c) {//c可为空
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

public static <T> void sort(T[] a, int fromIndex, int toIndex,
                                Comparator<? super T> c) {
        if (c == null) {//当c为空时,直接对数组elementData排序
            sort(a, fromIndex, toIndex);
        } else {
            rangeCheck(a.length, fromIndex, toIndex);
            if (LegacyMergeSort.userRequested)
                legacyMergeSort(a, fromIndex, toIndex, c);
            else
                TimSort.sort(a, fromIndex, toIndex, c, null, 0, 0);
        }
    }

替换

@Override
    @SuppressWarnings("unchecked")
    public void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);//判空
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值