Iterator在ArrayList中的源码实现

news/2024/7/3 11:41:53

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

获取迭代器

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的一个内部类,结构: 输入图片说明

首先看变量

int cursor;       // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;

**cursor 返回下个元素的下标索引,初始化为0

lastRet 上一个元素的下标索引,初始化为-1,因为当前元素下标为0时没有上一个元素

modCount 声明的变量如下,用于记录数组集合是否被修改过**

protected transient int modCount = 0;

使用到的方法如下:

trimToSize()
ensureExplicitCapacity()
add()
remove()
fastRemove()
clear()
addAll()
removeRange()
batchRemove()
sort()

再看一下, expectedModCount 除了初始化的时候被赋值了意外,只有在迭代过程中将modCount重新赋值给它, 其它任何时候它都不会变化。 因此,当我们用迭代器进行迭代的时候,单线程条件下,理论上expectedModCount = modCount 是恒成立的。 但在多线程环境下,就会出现二者不像等的情况。

hasNext()

public boolean hasNext() {
    return cursor != size;
}

**意思就是数组下表索引没有越界之前都是有元素的 **

next()

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

**获取当前索引下标元素,指针(cursor)后移,不多说。 **

remove源码

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


### 校验数组是否修改过(在迭代遍历过程中经常会抛出的异常)

这里输入代码

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

校验数组是否越界

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 指的是数组的容量(如果元素不为空觉得能得到元素的个数效率更高一点)

_总结

** 1.迭代器在ArrayList中的实现,起始是对对象数组的一系列操作。**

** 2.在List集合中可以使用迭代器的原因是ArrayList 中的内部类 Itr 实现了 Iterator接口 ** ** 3. 在对数组元素进行删除或者更新添加元素等操作时,单线程下最好用迭代器, 用传统的for循环或者foreach循环都将导致异常。 解决遍历过程中对集合进行修改的问题请参考 CopyOnWriteArrayList_**

转载于:https://my.oschina.net/xiaomingnevermind/blog/1802722


http://www.niftyadmin.cn/n/2891602.html

相关文章

List如何正确地在遍历时删除元素-EFFECTIVE STL 9

std::list::remove_if 遍历时删除元素的正确写法&#xff1a; list<int> l; for (list<int>::iterator iterl.begin();iter!l.end;) {if (condition (*iter) 0 ){iterl.erase(iter); // 注意此处要用iter接受l.erase(iter)的返回值}else{iter;} } 删除头部第一…

xcodebuild结合shell脚本实现iOS工程一键打包

提示&#xff1a;这里只列举企业证书&#xff08;enterprise&#xff09;打包、AdHoc、AppStore只需要简单修改即可完成。 探究过程&#xff1a; &#xff08;1&#xff09;工程需要手动配置证书、使用xcodebuild打包 首先需要在工程目录同级建立plist文件、这是xcodbuild必带参…

ExtJS实战(4)-struts

既然是说SSH&#xff0c;那就少不了WEB层的struts.我们以前做过一个小型的HRMS&#xff0c;采用的是Spring自己的MVC框架。这一次&#xff0c;我们还是用老牌的Struts。这是一个非常简单而且容易学习的框架&#xff0c;如果大家对它还不是非常了解&#xff0c;请先参考我的相关…

DAPP 开发直通车-如何基于NEL 轻钱包来开发DAPP

之前做了 DAPP 开发直通车&#xff0c;通讲了一下开发一个DAPP的过程。但是涉及多工种&#xff0c;多步骤。入手还是非常困难的。经过不懈的努力&#xff0c;做了很多铺垫工作之后&#xff0c;我终于可以告诉你&#xff1a;开发DAPP for NEO&#xff0c;从未如此简单绿谷镇楼。…

C++11 条件变量类

0.引入 本文选自《C并发实战-第二版》附录D-线程类参考-D.2 <condition_variable>头文件 1.<condition_variable>头文件 <condition_variable>头文件提供了条件变量的定义。其作为基本同步机制&#xff0c;允许被阻塞的线程在某些条件达成或超时时&#xf…

二、Java面向对象(8)_继承思想——继承关系

2018-05-01 劳动是为了更好的享受生活。 继承思想 一、继承的概念 继承是面向对象最显著的一个特性。继承是从已有的类中派生出新的类&#xff0c;新的类能吸收已有类的某些数据属性和行为&#xff0c;并能扩展新的能力。 继承就是子类继承父类的特征和行为&#xff0c;使得子类…

知识点汇总

Java JWT token 什么是token认证&#xff1f; 基于token的用户认证是一种服务端无状态的认证方式&#xff0c;所谓服务端无状态指的token本身包含登录用户所有的相关数据&#xff0c;而客户端在认证后的每次请求都会携带token&#xff0c;因此服务器端无需存放token数据。 当用…

ExtJS实战(5)-dwr

SSH这三个巨擘已经现身了&#xff0c;接下来就轮到我们小型的AJAX框架DWR了。做好DWR的准备工作&#xff1a;导入JAR包->在web.xml配置核心Servlet->编写核心配置文件dwr.xml,我在前面的应用中已经详细介绍过DWR&#xff0c;这里就简单地说一下。DWR是一个JAVA世界里的AJ…