Java ArrayList 源码解读

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_32197439/article/details/82316528

ArrayList 源码解读

  • 数据结构
    • 底层通过数组实现 可以称为 动态数组
  • 构造函数
// 初始化为空,transient Object[] elementData;
public ArrayList() {
        this.elementData = DEFAULTCAPACITY_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();// Object[]
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class) toArray方法出错
                // 数组拷贝到arraylist的对象数组上,会判断是copy还是反射newInstance
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
  • 增加
    • add(e)
    • add(index,e)
    • addAll()
public boolean add(E e) {
        // 判断add后是否需要扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;// 增加的元素放到数组末尾 size+1
        return true;
    }

private void ensureCapacityInternal(int minCapacity) {
        // 当前是否为空
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

private void ensureExplicitCapacity(int minCapacity) {
        modCount++; // 修改次数增加

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
// 扩容增量为1/2
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);// 3/2*oldCapacity
        if (newCapacity - minCapacity < 0)// 扩一半后还不够则用add后的容量
            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);
    }

// 在指定位置插入元素
public void add(int index, E element) {
        // 校验是否数组越界 则抛异常
        rangeCheckForAdd(index);
        // 与add(e)一样 看是否需要扩容 修改次数+1
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // index后元素后移一位
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        // e放入数组index位置
        elementData[index] = element;
        size++;
    }

// 添加集合
public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // 确认是否需要扩容
        System.arraycopy(a, 0, elementData, size, numNew); // 复制数组
        size += numNew; // 修改list的size
        return numNew != 0; // 是否追加成功
    }
// 指定index 插入集合
public boolean addAll(int index, Collection<? extends E> c) {
        // 是否越界
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);// 扩容

        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;
    } 
  • 删除 容量不会减少
    • remove(index)
    • remove(Object)
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);
        // 引用失效 以便GC
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
// 删除指定元素
public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);// 根据index移除元素
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
// 批量移除
public boolean removeAll(Collection<?> c) {
        // 非空校验
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;// w:批量删除后还剩下多少元素
        boolean modified = false;
        try {
            for (; r < size; r++)
        // 如果集合中不包含数组的这一元素则保留
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.

//出现异常会导致 r !=size , 则将出现异常处后面的数据全部复制覆盖到数组里。
            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++)
                    // GC
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
  • 修改
    • set(index,e)
public E set(int index, E element) {
        rangeCheck(index); 越界校验

        E oldValue = elementData(index);//根据下标取出原来的值
        elementData[index] = element;// 将新值替代原来的值
        return oldValue;// 返回旧值
    }

    • get(index) 高效
public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }
  • clear操作
public void clear() {
    modCount++;//修改modCount
    // clear to let GC do its work
    for (int i = 0; i < size; i++)  //将所有元素置null
        elementData[i] = null;

    size = 0; //修改size 
}
  • 包含 contain
public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
// 查找出的下标是否 >= 0 找不到return -1   
public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
  • 迭代器Iterator
public Iterator<E> iterator() {
        return new Itr();
    }

private class Itr implements Iterator<E> {
        int cursor;       // 游标
        int lastRet = -1; // 上一次返回的元素 (删除的标志位)
        int expectedModCount = modCount; 用于判断集合十分修改过的标志

        public boolean hasNext() {
            return cursor != size;// 是否还有下一个元素 是否移动到尾巴
        }

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

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
            // remove操作会修改modCount 
                ArrayList.this.remove(lastRet);
                cursor = lastRet; 要删除的游标
                lastRet = -1; 不重复删除 修改删除的标志位
                expectedModCount = modCount; 更新标志
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
  • trimToSize
public void trimToSize() {
        modCount++; // 修改次数+1
        if (size < elementData.length) {
//将elementData中空余的空间(包括null值)去除
//例如:数组长度为10,其中只有前三个元素有值,其他为空,那么调用该方法之后,数组的长度变为3.
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }
  • 小结

    • 增加和删除会修改modCount,改和查不会
    • 扩容需要复制数组,批量remove需要找出两集合的共有元素及数组复制 效率不高
    • 与vector区别 vector ArrayList

      • 线程安全 synchronize 不安全
      • 扩容倍数 翻倍 1/2

        • 实现的RandomAccess接口 起到标记作用,能够快速随机地访问存储的元素
if(list instanceof RandomAccess)// 根据list的特性 选择不同迭代方法
  • 结论
    • ArrayList 使用 for 循环遍历优于迭代器遍历
    • LinkedList 使用 迭代器遍历优于 for 循环遍历

猜你喜欢

转载自blog.csdn.net/sinat_32197439/article/details/82316528