• Iteratable:
public interface Iterable<T> {

    Iterator<T> iterator();

    default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
} default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
}
    • Iteratable接口提供了iterator()方法。
    • Collection接口继承了Iteratable,由实现Collection的ArrayList、Hashset等来实现方法。
  • Iterator:

public interface Iterator<E> {

    boolean hasNext();

    E next();

    default void remove() {
throw new UnsupportedOperationException("remove");
} default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
    • Iterator接口在ArrayList、LinkedList等类中都有内部类实现
    • Iterator接口的不当使用会导致抛出ConcurrentModificationException:
    List<String> famousList = new ArrayList<>();
famousList.add("Sheldon");
famousList.add("Sherlock");
famousList.add("Batman");
famousList.add("Optimus Prime"); for (String famous :
famousList) {
famousList.remove(famous);
}

上面的代码之所以会抛出ConcurrentModificationException异常的原因:

  • 增强for循环其实在编译生成字节码后会发现,就是转化为通过调用iterator的hasNext()、next()函数来遍历集合,查看ArrayList的iterator的实现代码:
    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();
}
}

从以上代码可知,当调用next()函数的时候,会先调用checkForComodification函数来检查集合的modCount与expectedModCount是否相等,若不相等则抛出错误。来到这里就能知道,在使用iterator遍历集合的时候,使用集合的remove、add等函数,就会导致modCount和expectedModCount不一致,从而导致异常抛出。

  • 正确的做法:
    Iterator<String> iterator = famousList.iterator();
for (;iterator.hasNext();){
String famous=iterator.next();
System.out.println(famous);
if ("Batman".equals(famous)){
iterator.remove();
break;
}
}
System.out.println(famousList.size());

或者:

    for (int i = 0; i < famousList.size(); i++) {
System.out.println(famousList.get(i));
if ("Batman".equals(famousList.get(i))){
famousList.remove(famousList.get(i));
break;
}
}
System.out.println(famousList.size());
  • ListIterator:
public interface ListIterator<E> extends Iterator<E> {

    boolean hasNext();

    E next();

    //判断cursor前是否有元素
boolean hasPrevious(); //获得cursor前一个元素,并且cursor后退一位
E previous(); //返回cursor元素的index
int nextIndex(); //返回cursor前一个元素的index
int previousIndex(); void remove(); //更新上一次调用next、previous返回的元素,也就是iterator最后一次操作的元素,没有调用next、previous前调用的话会抛出IllegalStateExceptiony异常
void set(E e); //向cursor前插入元素
void add(E e); }
  • ListIterator由实现List接口的集合类通过以下两种方法返回:
    public ListIterator<E> listIterator() {
return new ListItr(0);
} //返回指定cursor位置的listIterator
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}

相比Iterator,多了add、set以及previous等方法。

Iterator、Iteratable与ListIterator的更多相关文章

  1. 源码阅读—Iterator接口和LIstIterator接口

    在继续看ArrayList源码之前,先了解Iterator接口和ListIterator接口,下篇文章详细讲解ArrayList是如何实现它们的. 我们知道,接口只是一种规范,当继承接口并实现其中的方 ...

  2. 详解 迭代器 —— Iterator接口、 ListIterator接口 与 并发修改异常

    (请关注 本人"Collection集合"博文--<详解 Collection集合>) Iterator接口(迭代器): 概述: 对 collection 进行迭代的迭 ...

  3. Iterator之ListIterator简介

    ListIterator是什么? (参考自百度百科) java中的ListIterator在Iterator基础上提供了add.set.previous等对列表的操作.但是ListIterator跟I ...

  4. Iterator和ListIterator区别

    我们在使用List,Set的时候,为了实现对其数据的遍历,我们经常使用到了Iterator(迭代器).使用迭代器,你不需要干涉其遍历的过程,只需要每次取出一个你想要的数据进行处理就可以了. 但是在使用 ...

  5. Java容器类源码分析之Iterator与ListIterator迭代器(基于JDK8)

    一.基本概念 迭代器是一个对象,也是一种设计模式,Java有两个用来实实现迭代器的接口,分别是Iterator接口和继承自Iterator的ListIterator接口.实现迭代器接口的类的对象有遍历 ...

  6. 09 Collection,Iterator,List,listIterator,Vector,ArrayList,LinkedList,泛型,增强for,可变参数,HashSet,LinkedHashSet,TreeSet

    09 Collection,Iterator,List,listIterator,Vector,ArrayList,LinkedList,泛型,增强for,可变参数,HashSet,LinkedHas ...

  7. Java学习笔记之Iterator和ListIterator

    原文:https://blog.csdn.net/GongchuangSu/article/details/51514380 Iterator接口是对collection进行迭代的迭代器,ListIt ...

  8. Iterator接口(迭代器)

    目录 前言 原理 方法 异常 Iterator接口(迭代器) 前言 一般遍历数组都是采用for循环或者增强for,这两个方法也可以用在集合框架,但是还有一种方法是采用迭代器遍历集合框架,它是一个对象, ...

  9. 设计模式 笔记 迭代器模式 Iterator

    //---------------------------15/04/26---------------------------- //Iterator 迭代器模式----对象行为型模式 /* 1:意 ...

随机推荐

  1. java工程师

    java工程师 职位描述 1.参与产品后台需求和产品经理确定: 2.主导产品后台架构设计和前端通讯协议: 3.设计后台的架构,能支持大的并发量: 4.优化后台的性能,能保证接口的流畅性: 5.负责解决 ...

  2. Android本地广播

    Android中使用的广播一般是系统全局广播,即发出的广播可以被其他任何应用程序接收到,并且我们也可以接收来自于其他任何应用程序的广播.这样就很容易会引起安全性的问题,比如说我们发送的一些携带关键性数 ...

  3. 一个对iBatis的总结写的不错(转载)

    转载自:http://blog.csdn.net/panxueji/article/details/9852795 一. ibatis介绍 ibatis始于2002年,2010年更名为mybatis, ...

  4. STL_算法_04_算术和生成算法

    ◆ 常用的算术和生成算法: 1.1.求和( accumulate 是求和的意思)(对指定范围内的元素求和,然后结果再加上一个由val指定的初始值.) T accumulate(iteratorBegi ...

  5. [ios]"The identity used to sign the executable is no longer valid"错误解决方法

    重新去开发者网站,申请一遍profiles 参考:http://www.bubuko.com/infodetail-982908.html 我出现这个错误的情况,程序提交app store之后,第二天 ...

  6. [ios]MKMapView中使用MKPolyline画线

    参考:http://blog.sina.com.cn/s/blog_9e8867eb0101dt76.html 首先在MapView.h中 #import <MapKit/MapKit.h> ...

  7. 雷林鹏分享:Ruby 方法

    Ruby 方法 Ruby 方法与其他编程语言中的函数类似.Ruby 方法用于捆绑一个或多个重复的语句到一个单元中. 方法名应以小写字母开头.如果您以大写字母作为方法名的开头,Ruby 可能会把它当作常 ...

  8. Android动画(Animations)

    动画类型Android的animation由四种类型组成 XML中 alpha  : 渐变透明度动画效果 scale  :渐变尺寸伸缩动画效果 translate  : 画面转换位置移动动画效果 ro ...

  9. Confluence 6 使用 LDAP 授权连接一个内部目录概述

    你可以为你的 Confluence 连接 LDAP 服务器使用使用委托认证.这个意思是 Confluence 将会设置一个内部目录,这个目录仅被用来处理 LDAP 的授权. 这个设置将会为尝试登录系统 ...

  10. hdu1358 kmp的next数组

    For each prefix of a given string S with N characters (each character has an ASCII code between 97 a ...