Iterator在ArrayList中的源码实现

获取迭代器

List<LinkedHashMap> list = new ArrayList<>();
        Iterator iterator = list.iterator();

iterator()方法实现

public Iterator<E> iterator() {
        return new Itr();
    }

Itr 源码

/**
 * An optimized version of AbstractList.Itr
 */
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;

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

Itr 为ArrayList的一个内部类,结构: 输入图片说明

remove源码

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

数组复制:

public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);

arraycopy 的源码在这

System.arraycopy 源码

我翻看了下注释说明: 敲重点:

  • If the <code>src</code> and <code>dest</code> arguments refer to the
  • same array object, then the copying is performed as if the
  • components at positions <code>srcPos</code> through
  • <code>srcPos+length-1</code> were first copied to a temporary
  • array with <code>length</code> components and then the contents of
  • the temporary array were copied into positions
  • <code>destPos</code> through <code>destPos+length-1</code> of the
  • destination array.

就是说,原数组与将要复制的数组为同一个的时候,就是元素之间的移动。其它的实现暂时不解释。 于是,我们可以理解为:删除指定数组下标index位置的元素,然后从数组下表index+1的位置开始向前移动size-index-1 个元素,学过数据结构的童鞋 这里就很好理解啦,不多做解释。 这里的size 指的是数组的容量(如果元素不为空觉得能得到元素的个数效率更高一点)

关于其它方法,以后再加。

猜你喜欢

转载自my.oschina.net/xiaomingnevermind/blog/1802722