salvete

ArrayList源码解析

ArrayList源码解析

实现的接口

  • List
  • RandomAccess(保证了可以随机访问元素)
  • Cloneable
  • java.io.Serializable

父类

  • AbstractList

 构造函数

  • ArrayList()
/**
     * 无参构造函数,注意此处使用的数据缓存是DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     */
    public ArrayList() {
        // 使用无参构造函数是,使用 DEFAULTCAPACITY_EMPTY_ELEMENTDATA
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
  • ArrayList(int initialCapacity)
/**
     * 构造一定容量的ArrayList
     * @param initialCapacity 容量大小
     */

    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            // 当容量大小为0时, 使用EMPTY_ELEMENTDATA
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
  • ArrayList(Collection<? extends E> c)
/**
     * 通过一个已经存在的集合来构造ArrayList
     * @param c 一个一个,该集合里面元素的类型为ArrayList元素类型的子类型
     */

    public ArrayList(Collection<? extends E> c) {
        Object[] a = c.toArray();
        if ((size = a.length) != 0) {
            // 如果二者类型一致,那么数组直接赋值
            if (c.getClass() == ArrayList.class) {
                elementData = a;
            } else {
                // 数据类型不一致,那么重新以Object[]类型复制一份
                elementData = Arrays.copyOf(a, size, Object[].class);
            }
        } else {
            // replace with empty array.
            elementData = EMPTY_ELEMENTDATA;
        }
    }

 

其余函数

 

    /**
     * 缩小数组到size大小,来减小占用的空间
     */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 扩容
     * @param minCapacity 最终的结果为max(minCapacity, elementData.lenth * 1.5,DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
     */
    public void ensureCapacity(int minCapacity) {
        if (minCapacity > elementData.length
            && !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
                 && minCapacity <= DEFAULT_CAPACITY)) {
            modCount++;
            grow(minCapacity);
        }
    }

   
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    
    /**
     * 将原来的数组扩容
     * @param minCapacity
     * @return
     */
    private Object[] grow(int minCapacity) {
        return elementData = Arrays.copyOf(elementData,
                                           newCapacity(minCapacity));
    }

    private Object[] grow() {
        return grow(size + 1);
    }

    /**
     * 计算新的容量大小 = max(minCapacity, elementData.length * 1.5 , DEFAULT_CAPACITY)
     * @param minCapacity
     * @return
     */
    private int newCapacity(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        // 新的大小为原来的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity <= 0) {
            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                return Math.max(DEFAULT_CAPACITY, minCapacity);
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            return minCapacity;
        }
        return (newCapacity - MAX_ARRAY_SIZE <= 0)
            ? newCapacity
            : hugeCapacity(minCapacity);
    }

    // 大容量数组的大小, 与MAX_ARRAY_SIZE和Integer.MAX_VALUE比较
    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 int size() {
        return size;
    }

    
    // 判断是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    /
    // 判断是否包含某个元素, 复杂度O(n)
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    
    // 判断[0,size)区间内是否存在某个元素
    public int indexOf(Object o) {
        return indexOfRange(o, 0, size);
    }

    // 判读[begin,end)区间内是否存在某个元素
    int indexOfRange(Object o, int start, int end) {
        Object[] es = elementData;
        if (o == null) {
            for (int i = start; i < end; i++) {
                if (es[i] == null) {
                    return i;
                }
            }
        } else {
            for (int i = start; i < end; i++) {
                if (o.equals(es[i])) {
                    return i;
                }
            }
        }
        return -1;

        /**
         * 另一种写法
         * for (int i = start; i < end; i ++)
         * {
         *      if (Objects.equals(o,es[i]))
         *          return i;
         * }
         * 
         * return -1;
         */
    }

    
    // 返回最后出现的位置
    public int lastIndexOf(Object o) {
        return lastIndexOfRange(o, 0, size);
    }

    int lastIndexOfRange(Object o, int start, int end) {
        Object[] es = elementData;
        if (o == null) {
            for (int i = end - 1; i >= start; i--) {
                if (es[i] == null) {
                    return i;
                }
            }
        } else {
            for (int i = end - 1; i >= start; i--) {
                if (o.equals(es[i])) {
                    return i;
                }
            }
        }
        return -1;


        /**
         * 另一种写法
         *  for (int i = end - 1; i >= 0; i --)
         * {
         *      if (Objects.equals(o,es[i]))
         *          return i;
         * }
         * 
         * return -1;
         */

    }

    
    /**
     * 浅复制
     * @return 本实例的一个拷贝
     */
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    
    /**
     * 这个方法返回一个本实例数组的备份,因此是安全的,可以对其进行修改而不会伤害到
     * 本实例的数组
     * @return
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    
    /**
     * 该函数返回本地数组的内容
     * 如果a的大小小于本地数组的大小,那么则将本地数组的类型转换为a的类型之后返回
     * 否则,将本地数组复制到a数组中后,将后面紧跟着的那个元素设置为null
     * @param <T>
     * @param a
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            // 返回本地数组的内容,但是类型进行转换,变为a中元素的类型
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        //否则,a的大小大于本地数组的大小,将本地数组的内容进行复制
        System.arraycopy(elementData, 0, a, 0, size);
        //将后面紧跟着的那个元素置为null
        if (a.length > size)
            a[size] = null;
        return a;
    }

    // Positional Access Operations

    // 返回一个元素, 将其强制转换为E类型
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    // 获取元素,静态方法
    @SuppressWarnings("unchecked")
    static <E> E elementAt(Object[] es, int index) {
        return (E) es[index];
    }

    
    /**
     * 返回元素
     * @param index
     * @return
     */
    public E get(int index) {
        Objects.checkIndex(index, size);
        return elementData(index);
    }

    
    /**
     * 设置特定位置的元素值
     * @param index
     * @param element
     * @return 返回原先该位置的元素值
     */
    public E set(int index, E element) {
        Objects.checkIndex(index, size);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

   //添加元素
    private void add(E e, Object[] elementData, int s) {
        if (s == elementData.length)
            elementData = grow();
        elementData[s] = e;
        size = s + 1;
    }

   
    /**
     * 在末尾添加一个元素
     * @param e
     * @return
     */
    public boolean add(E e) {
        modCount++;
        add(e, elementData, size);
        return true;
    }

    
    /**
     * 在特定位置加入一个元素
     * @param index
     * @param element
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        modCount++;
        final int s;
        Object[] elementData;
        if ((s = size) == (elementData = this.elementData).length)
            elementData = grow();
        //将该位置和之后的元素向后挪一个单位
        System.arraycopy(elementData, index,
                         elementData, index + 1,
                         s - index);
        //将该位置的元素进行替换
        elementData[index] = element;
        size = s + 1;
    }

    
    /**
     * 删除某个特定位置的元素
     * @param index
     * @return
     */
    public E remove(int index) {
        Objects.checkIndex(index, size);
        final Object[] es = elementData;

        @SuppressWarnings("unchecked") E oldValue = (E) es[index];
        //将该位置以后的元素向前移动一个单位
        fastRemove(es, index);

        return oldValue;
    }

    // 删掉元素
    public boolean remove(Object o) {
        final Object[] es = elementData;
        final int size = this.size;
        int i = 0;
        found: {
            if (o == null) {
                for (; i < size; i++)
                    //如果相等,跳出循环
                    if (es[i] == null)
                        break found;
            } else {
                for (; i < size; i++)
                    //相等则跳出循环
                    if (o.equals(es[i]))
                        break found;
            }
            return false;
        }
        fastRemove(es, i);
        return true;
    }


    // 将i之后的元素向前移动一个单元
    private void fastRemove(Object[] es, int i) {
        modCount++;
        final int newSize;
        if ((newSize = size - 1) > i)
            System.arraycopy(es, i + 1, es, i, newSize - i);
        es[size = newSize] = null;
    }

   
    // 清空所有元素,size变为0
    public void clear() {
        modCount++;
        final Object[] es = elementData;
        for (int to = size, i = size = 0; i < to; i++)
            es[i] = null;
    }

    
    /**
     * 添加一个集合里面的元素
     * @param c
     * @return
     */
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        modCount++;
        int numNew = a.length;
        if (numNew == 0)
            return false;
        Object[] elementData;
        final int s;
        // 如果此时的容量不够,那么应该扩容
        if (numNew > (elementData = this.elementData).length - (s = size))
            elementData = grow(s + numNew);
        System.arraycopy(a, 0, elementData, s, numNew);
        size = s + numNew;
        return true;
    }

    
    /**
     * 集合中的所有元素添加到指定位置开始的地方
     * @param index
     * @param c
     * @return
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        modCount++;
        int numNew = a.length;
        if (numNew == 0)
            return false;
        Object[] elementData;
        final int s;
        if (numNew > (elementData = this.elementData).length - (s = size))
            elementData = grow(s + numNew);

        int numMoved = s - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index,
                             elementData, index + numNew,
                             numMoved);
        System.arraycopy(a, 0, elementData, index, numNew);
        size = s + numNew;
        return true;
    }

    
    /**
     * 删掉范围内的元素
     * @param fromIndex
     * @param toIndex
     */
    protected void removeRange(int fromIndex, int toIndex) {
        if (fromIndex > toIndex) {
            throw new IndexOutOfBoundsException(
                    outOfBoundsMsg(fromIndex, toIndex));
        }
        modCount++;
        shiftTailOverGap(elementData, fromIndex, toIndex);
    }

    /**
     * 通过简单的复制,覆盖掉范围内的元素,之后的位置置为null
     * @param es
     * @param lo
     * @param hi
     */
    /** Erases the gap from lo to hi, by sliding down following elements. */
    private void shiftTailOverGap(Object[] es, int lo, int hi) {
        System.arraycopy(es, hi, es, lo, size - hi);
        for (int to = size, i = (size -= hi - lo); i < to; i++)
            es[i] = null;
    }

    
    /**
     * 删掉集合那些在集合c中的元素
     * @param c
     * @return
     */
    public boolean removeAll(Collection<?> c) {
        return batchRemove(c, false, 0, size);
    }

    
    /**
     * 留下那些在结合c中的元素
     * @param c
     * @return
     */
    public boolean retainAll(Collection<?> c) {
        return batchRemove(c, true, 0, size);
    }

    /**
     * 工具函数
     * @param c 集合c
     * @param complement 判断是否留下在c中的元素
     * @param from 起点
     * @param end 终点
     * @return
     */
    boolean batchRemove(Collection<?> c, boolean complement,
                        final int from, final int end) {
        Objects.requireNonNull(c);
        final Object[] es = elementData;
        int r;
        // Optimize for initial run of survivors
        for (r = from;; r++) {
            if (r == end)
                return false;
            // 第一个不符合要求的元素
            if (c.contains(es[r]) != complement)
                break;
        }
        int w = r++;
        try {
            for (Object e; r < end; r++)
                //只有符合要求,才将w往后移动,类似的做法还有去掉数组中的重复元素,都是双指针
                if (c.contains(e = es[r]) == complement)
                    es[w++] = e;
        } catch (Throwable ex) {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            System.arraycopy(es, r, es, w, end - r);
            w += end - r;
            throw ex;
        } finally {
            modCount += end - w;
            // 此时,(w,end)之间的元素是不合法的,需要删除掉
            shiftTailOverGap(es, w, end);
        }
        return true;
    }

ListIteratorItr迭代器的实现

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;

        // prevent creating a synthetic constructor
        Itr() {}

        // 判断是否还有元素
        public boolean hasNext() {
            return cursor != size;
        }

        // 获取下一个元素,同时将当前指针加1
        @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();
            // 当前指针加1
            cursor = i + 1;
            // 返回刚刚跳过的元素
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            // 首先判断是否存在上一元素
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                // 此时的cursor指向的是被移除元素的下一元素
                cursor = lastRet;
                // 上一元素为-1
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i < size) {
                final Object[] es = elementData;
                if (i >= es.length)
                    throw new ConcurrentModificationException();
                for (; i < size && modCount == expectedModCount; i++)
                    action.accept(elementAt(es, i));
                // update once at end to reduce heap write traffic
                cursor = i;
                lastRet = i - 1;
                checkForComodification();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

  

posted on 2021-10-31 19:18  salvete  阅读(24)  评论(0编辑  收藏  举报

导航