当前位置:   article > 正文

Iterator(迭代器)的用法及其背后机制的探究_this.iterator()

this.iterator()

Iterator 怎么使用?有什么特点?

Java中的Iterator功能比较简单,并且只能单向移动:

(1) 使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。注意:iterator()方法是java.lang.Iterable接口,被Collection继承。

(2) 使用next()获得序列中的下一个元素。

(3) 使用hasNext()检查序列中是否还有元素。

(4) 使用remove()将迭代器新返回的元素删除。

Iterator是Java迭代器最简单的实现,为List设计的ListIterator具有更多的功能,它可以从两个方向遍历List,也可以从List中插入和删除元素。

 Iterator 和 ListIterator 有什么区别?

  • Iterator可用来遍历Set和List集合,但是ListIterator只能用来遍历List。 

  • Iterator对集合只能是前向遍历,ListIterator既可以前向也可以后向。 

  • ListIterator实现了Iterator接口,并包含其他的功能,比如:增加元素,替换元素,获取前一个和后一个元素的索引,等等。

 

迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构。迭代器通常被称为“轻量级”对象,因为创建它的代价小。

  Java中的Iterator功能比较简单,并且只能单向移动:

  (1) 使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。注意:iterator()方法是java.lang.Iterable接口,被Collection继承。

  (2) 使用next()获得序列中的下一个元素。

  (3) 使用hasNext()检查序列中是否还有元素。

  (4) 使用remove()将迭代器新返回的元素删除。

只要看看下面这个例子就一清二楚了:

  1. import java.util.*;
  2. public class Muster {
  3.     public static void main(String[] args) {
  4.         ArrayList list = new ArrayList();
  5.         list.add("a");
  6.         list.add("b");
  7.         list.add("c");
  8.         Iterator it = list.iterator();
  9.         while(it.hasNext()){
  10.             String str = (String) it.next();
  11.             System.out.println(str);
  12.         }
  13.     }
  14. }

 

运行结果:

a
b
c

可以看到,Iterator可以不用管底层数据具体是怎样存储的,都能够通过next()遍历整个List。

但是,具体是怎么实现的呢?背后机制究竟如何呢?

这里我们来看看Java里AbstractList实现Iterator的源代码:

  1. public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { // List接口实现了Collection<E>, Iterable<E>
  2.    protected AbstractList()
  3.    } 
  4.   ... 
  5.   public Iterator<E> iterator()
  6.    return new Itr();  // 这里返回一个迭代器
  7.   } 
  8. private class Itr implements Iterator<E> {  // 内部类Itr实现迭代器
  9.     
  10.   int cursor = 0
  11.   int lastRet = -1
  12.   int expectedModCount = modCount; 
  13.   public boolean hasNext()// 实现hasNext方法
  14.       return cursor != size(); 
  15.   } 
  16. public E next()// 实现next方法
  17.    checkForComodification(); 
  18.    try { 
  19.        E next = get(cursor); 
  20.        lastRet = cursor++; 
  21.        return next; 
  22.   } catch (IndexOutOfBoundsException e) { 
  23.      checkForComodification(); 
  24.      throw new NoSuchElementException(); 
  25. public void remove() {
  26. if (lastRet < 0)
  27. throw new IllegalStateException();
  28. checkForComodification();
  29. try {
  30. AbstractList.this.remove(lastRet);
  31. if (lastRet < cursor)
  32. cursor--;
  33. lastRet = -1;
  34. expectedModCount = modCount;
  35. } catch (IndexOutOfBoundsException e) {
  36. throw new ConcurrentModificationException();
  37. }
  38. }
  39. final void checkForComodification() {
  40. if (modCount != expectedModCount)
  41. throw new ConcurrentModificationException();
  42. }
  43. }


这部分代码不难看懂,唯一难懂的是remove操作里涉及到的expectedModCount = modCount;可以看到,实现next()是通过get(cursor),然后cursor++,通过这样实现遍历。

在网上查到说这是集合迭代中的一种“快速失败”机制,这种机制提供迭代过程中集合的安全性。

从源代码里可以看到增删操作都会使modCount++,通过和expectedModCount的对比,迭代器可以快速的知道迭代过程中是否存在list.add()类似的操作,存在的话快速失败!

在第一个例子基础上添加一条语句:

  1. import java.util.*;
  2. public class Muster {
  3.     public static void main(String[] args) {
  4.         ArrayList list = new ArrayList();
  5.         list.add("a");
  6.         list.add("b");
  7.         list.add("c");
  8.         Iterator it = list.iterator();
  9.         while(it.hasNext()){
  10.             String str = (String) it.next();
  11.             System.out.println(str);
  12.             list.add("s");        //添加一个add方法
  13.         }
  14.     }
  15. }


这就会抛出一个下面的异常,迭代终止。运行结果:
Exception in thread "main" java.util.ConcurrentModificationException
  at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
  at java.util.ArrayList$Itr.next(Unknown Source)
  at com.hasse.Muster.main(Muster.java:11)

 

关于modCount,API解释如下:

The number of times this list has been structurally modified. Structural modifications are those that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.

也就是说,modCount记录修改此列表的次数:包括改变列表的结构,改变列表的大小,打乱列表的顺序等使正在进行迭代产生错误的结果。

Tips:仅仅设置元素的值并不是结构的修改

我们知道的是ArrayList是线程不安全的,如果在使用迭代器的过程中有其他的线程修改了List就会抛出ConcurrentModificationException,这就是Fail-Fast机制。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/179626
推荐阅读
相关标签
  

闽ICP备14008679号