JAVA基础---ArrayList源码分析

构造方法

    transient Object[] elementData; // non-private to simplify nested class access

    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    
 public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
 private static final Object[] 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);
        }
    }
 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;
        }
    }

// c.toArray might (incorrectly) not return Object[] (see 6260652) c.toArray() 返回的不一定是Object[]

插入

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 static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { // elementData为空的情况下,如果最小容量小鱼10则返回10
        //  return (a >= b) ? a : b;
            return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
        }
        // 否则返回最小容量
        return minCapacity;
    }
 private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0) // elementData小于minCapacity 则进行扩容
            grow(minCapacity);
    }

modCount++;这里涉及到很多问题包括我们的快速失败,并发修改等。
在这里插入图片描述
在这里插入图片描述
果我们我们用foreach删除的元素刚好是最后一个,删除完成前cursor刚好等于size的大小。但是,删除完成后size的数量减1, 但是cursor并没有变化。导致下一次循环不相等继续向下执行,导致检查数组不通过,抛出java.util.ConcurrentModificationException

  private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);// oldCapacity + oldCapacity / 2 = 1.5 oldCapacity 
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)// Integer.MAX_VALUE - 8;
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

arraylist的扩容没有盲目的容量+1,通过oldCapacity + (oldCapacity >> 1)将容量扩大到现在的1.5倍。再次判断扩容后的大小是否满足需要的长度,如果不够就扩大到需要的大小。这一步是为了确保在addAll(Collection<? extends E> c)方法中合并数组不会出现问题。
扩容之后,在size位置上插入元素,size+1,完成了一次插入。

private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

插入指定位置

 public void add(int index, E element) {
        rangeCheckForAdd(index); // 确保给定索引不会越界
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);// 将index之后的数组全部向后移动一位
        elementData[index] = element;
        size++;
    }
 private void rangeCheckForAdd(int index) {
        if (index > size || index < 0) 
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

批量插入

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 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 将最后一位置为null方便垃圾回收

        return oldValue;
    }

指定索引

 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
    }

arraylist还是比较容易理解的,最后我们复习一道常见的面试题。
ArrayList与LinkedList的实现和区别?

1.对ArrayList和LinkedList而言,在列表末尾增加一个元素所花的开销都是固定的。对ArrayList而言,主要是在内部数组中增加一项,指向所添加的元素,偶尔可能会导致对数组重新进行分配;而对LinkedList而言,这个开销是统一的,分配一个内部Entry对象。

2.在ArrayList的中间插入或删除一个元素意味着这个列表中剩余的元素都会被移动;而在LinkedList的中间插入或删除一个元素的开销是固定的。

3.LinkedList不支持高效的随机元素访问。

4.ArrayList的空间浪费主要体现在在list列表的结尾预留一定的容量空间,而LinkedList的空间花费则体现在它的每一个元素都需要消耗相当的空间

发布了29 篇原创文章 · 获赞 11 · 访问量 1868

猜你喜欢

转载自blog.csdn.net/chihaihai/article/details/101202827