Iterator的remove方法可保证从源集合中安全地删除对象(转)
如果对正在被迭代的集合进行结构上的改变(即对该集合使用add、remove或clear方法),那么迭代器就不再合法(并且在其后使用该迭代器将会有ConcurrentModificationException异常被抛出).
如果使用迭代器自己的remove方法,那么这个迭代器就仍然是合法的。
package chapter1; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; /**
* Created by MyWorld on 2016/3/3.
*/
public class FastFailResolver { public static void main(String[] args) {
Map<String, String> source = new HashMap<String, String>();
for (int i = 0; i < 10; i++) {
source.put("key" + i, "value" + i);
}
System.out.println("Source:" + source);
// fastFailSceneWhenRemove(source);
commonSceneWhenRemove(source); } private static void commonSceneWhenRemove(Map<String, String> source) {
Iterator<Map.Entry<String, String>> iterator = source.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (entry.getKey().contains("1")) {
iterator.remove();
}
}
System.out.println(source);
} private static void fastFailSceneWhenRemove(Map<String, String> source) {
for (Map.Entry<String, String> entry : source.entrySet()) {
if (entry.getKey().contains("1")) {
source.remove(entry.getKey());
}
}
System.out.println(source);
} }
3.在一个循环中删除一个列表中的元素
思考下面这一段在循环中删除多个元素的的代码
| 1 2 3 4 5 | ArrayList<String> list = newArrayList<String>(Arrays.asList("a","b","c","d"));for(inti=0;i<list.size();i++){    list.remove(i);}System.out.println(list); | 
输出结果是:
| 1 | [b,d] | 
在这个方法中有一个严重的错误。当一个元素被删除时,列表的大小缩小并且下标变化,所以当你想要在一个循环中用下标删除多个元素的时候,它并不会正常的生效。
与下面结合的一个示例:
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","a", "b",
                "c", "d"));
        for (int i = ; i < list.size(); i++) {
            if (list.get(i).equals("a")) {
                list.remove(i);
            }
        }
        System.out.println(list);
    }
输出:
[a, b, c, d]
即输出与预期不一致
你也许知道在循环中正确的删除多个元素的方法是使用迭代,并且你知道java中的foreach循环看起来像一个迭代器,但实际上并不是。考虑一下下面的代码:
| 1 2 3 4 5 6 | ArrayList<String> list = newArrayList<String>(Arrays.asList("a","b","c","d"));for(String s:list){    if(s.equals("a")){        list.remove(s);    }} | 
它会抛出一个ConcurrentModificationException异常。 相反下面的显示正常:
| 1 2 3 4 5 6 7 8 | ArrayList<String> list = newArrayList<String>(Arrays.asList("a","b","c","d"));Iterator<String> iter = list.iterator();while(iter.hasNext()){        String s = iter.next();        if(s.equals("a")){            iter.remove();    }} | 
.next()必须在.remove()之前调用。在一个foreach循环中,编译器会使.next()在删除元素之后被调用,因此就会抛出ConcurrentModificationException异常,你也许希望看一下ArrayList.iterator()的源代码。
http://www.cnblogs.com/softidea/p/4279574.html
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; public class IteratorTest{
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Test1");
list.add("Test2");
list.add("Test3");
list.add("Test4");
list.add("Test5"); for(Iterator<String> it = list.iterator();it.hasNext();){
if(it.next().equals("Test3")){
it.remove();
}
} for(String s : list){
System.out.println(s);
} }
}
Iterator 支持从源集合中安全地删除对象,只需在 Iterator 上调用 remove() 即可。这样做的好处是可以避免 ConcurrentModifiedException ,这个异常顾名思意:当打开 Iterator 迭代集合时,同时又在对集合进行修改。
有些集合不允许在迭代时删除或添加元素,但是调用 Iterator 的remove() 方法是个安全的做法。
java.util.ConcurrentModificationException详解
http://blog.csdn.net/smcwwh/article/details/7036663
【引言】
经常在迭代集合元素时,会想对集合做修改(add/remove)操作,类似下面这段代码:
for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
    Integer val = it.next();
    if (val == 5) {
        list.remove(val);
    }
}
运行这段代码,会抛出异常java.util.ConcurrentModificationException。
【解惑】
(以ArrayList来讲解)在ArrayList中,它的修改操作(add/remove)都会对modCount这个字段+1,modCount可以看作一个版本号,每次集合中的元素被修改后,都会+1(即使溢出)。接下来再看看AbsrtactList中iteraor方法
public Iterator<E> iterator() {
    return new Itr();
}
它返回一个内部类,这个类实现了iterator接口,代码如下:
private class Itr implements Iterator<E> {
    int cursor = 0;
    int lastRet = -1;
    int expectedModCount = modCount;
    public boolean hasNext() {
        return cursor != size();
    }
    public E next() {
        checkForComodification();
        try {
            E next = get(cursor);
            lastRet = cursor++;
            return next;
        } catch (IndexOutOfBoundsException e) {
            checkForComodification();
            throw new NoSuchElementException();
        }
    }
    public void remove() {
        if (lastRet == -1)
            throw new IllegalStateException();
        checkForComodification();
        try {
            AbstractList.this.remove(lastRet);
            if (lastRet < cursor)
                cursor--;
            lastRet = -1;
            // 修改expectedModCount 的值
            expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
            throw new ConcurrentModificationException();
        }
    }
    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
    }
在内部类Itr中,有一个字段expectedModCount ,初始化时等于modCount,即当我们调用list.iterator()返回迭代器时,该字段被初始化为等于modCount。在类Itr中next/remove方法都有调用checkForComodification()方法,在该方法中检测modCount == expectedModCount,如果不相当则抛出异常ConcurrentModificationException。
前面说过,在集合的修改操作(add/remove)中,都对modCount进行了+1。
在看看刚开始提出的那段代码,在迭代过程中,执行list.remove(val),使得modCount+1,当下一次循环时,执行 it.next(),checkForComodification方法发现modCount != expectedModCount,则抛出异常。
【解决办法】
如果想要在迭代的过程中,执行删除元素操作怎么办?
再来看看内部类Itr的remove()方法,在删除元素后,有这么一句expectedModCount = modCount,同步修改expectedModCount 的值。所以,如果需要在使用迭代器迭代时,删除元素,可以使用迭代器提供的remove方法。对于add操作,则在整个迭代器迭代过程中是不允许的。 其他集合(Map/Set)使用迭代器迭代也是一样。
当使用 fail-fast iterator 对 Collection 或 Map 进行迭代操作过程中尝试直接修改 Collection / Map 的内容时,即使是在单线程下运行,  java.util.ConcurrentModificationException 异常也将被抛出。   
Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 
Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。
但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。
有意思的是如果你的 Collection / Map 对象实际只有一个元素的时候, ConcurrentModificationException 异常并不会被抛出。这也就是为什么在 javadoc 里面指出: it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.
Iterator的remove方法可保证从源集合中安全地删除对象(转)的更多相关文章
- Java连载85-集合的Contains和Remove方法
		一.包含与删除两种方法解析 1.boolean contains(Object o);判断集合中是否包含某个元素. package com.bjpowernode.java_learning; imp ... 
- 如何正确遍历删除List中的元素(普通for循环、增强for循环、迭代器iterator、removeIf+方法引用)
		遍历删除List中符合条件的元素主要有以下几种方法: 普通for循环 增强for循环 foreach 迭代器iterator removeIf 和 方法引用 其中使用普通for循环容易造成遗漏元素的问 ... 
- Lambda 表达式遍历集合时用remove方法删除list集合中满足条件的元素问题
		一:循环遍历list集合的四种方式 简单for循环 iterator循环 增加for循环 Lanbda表达式 二:四种遍历方式的用法示例 //简单for循环 List<SalaryAdjustm ... 
- jquery 清空动态append添加元素,remove方法
		<html> <head> <script type="text/javascript" src="jquery-1.9.1.js" ... 
- ScheduledThreadPoolExecutor之remove方法
		之前用定时任务的线程池,设置了个任务,但是突然今天产品说,某些个操作需要中断某些任务(如果任务还没有执行),使其不能再到点执行了.于是查了API果然有这样一个方法. 一看API,需要移除的是一个Run ... 
- Android 源码中的设计模式
		最近看了一些android的源码,发现设计模式无处不在啊!感觉有点乱,于是决定要把设计模式好好梳理一下,于是有了这篇文章. 面向对象的六大原则 单一职责原则 所谓职责是指类变化的原因.如果一个类有多于 ... 
- Android 网络框架之Retrofit2使用详解及从源码中解析原理
		就目前来说Retrofit2使用的已相当的广泛,那么我们先来了解下两个问题: 1 . 什么是Retrofit? Retrofit是针对于Android/Java的.基于okHttp的.一种轻量级且安全 ... 
- 集合中list、ArrayList、LinkedList、Vector的区别、Collection接口的共性方法以及数据结构的总结
		List (链表|线性表) 特点: 接口,可存放重复元素,元素存取是有序的,允许在指定位置插入元素,并通过索引来访问元素 1.创建一个用指定可视行数初始化的新滚动列表.默认情况下,不允许进行多项选择. ... 
- Java中循环删除list中元素的方法总结
		印象中循环删除list中的元素使用for循环的方式是有问题的,但是可以使用增强的for循环,然后在今天使用的时候发现报错了,然后去科普了一下,发现这是一个误区.下面我们来一起看一下. Java中循环遍 ... 
随机推荐
- php7+apache的环境安装配置
			因为刚开始接触php,所以要对php的开发环境进行搭建. 1.首先到Apache的官网下载最新版: http://httpd.apache.org/download.cgi: 参照该网址配置Apach ... 
- Google Guava学习笔记——基础工具类Joiner的使用
			Guava 中有一些基础的工具类,如下所列: 1,Joiner 类:根据给定的分隔符把字符串连接到一起.MapJoiner 执行相同的操作,但是针对 Map 的 key 和 value. 2,Spli ... 
- 在mac下使用brew和brew cask轻松实现软件安装
			Brew(homebrew) 1.简介 Brew 是 Mac 下面的包管理工具,通过 Github 托管适合 Mac 的编译配置以及 Patch,可以方便的安装开发工具. Mac 自带ruby 所以安 ... 
- Codeforces Round #349 (Div. 1)  B. World Tour 最短路+暴力枚举
			题目链接: http://www.codeforces.com/contest/666/problem/B 题意: 给你n个城市,m条单向边,求通过最短路径访问四个不同的点能获得的最大距离,答案输出一 ... 
- 02.Apache FtpServer使用数据库管理用户
			1.创建数据库及表 使用\apache-ftpserver-1.0.6\res\ftp-db.sql建表,内容如下: CREATE TABLE FTP_USER ( userid VARCHAR(64 ... 
- 【BZOJ】【3156】防御准备
			DP/斜率优化 斜率优化的裸题…… sigh……又把$10^6$当成10W了……RE了N发 这题还是很水的 当然逆序也能做……不过还是整个反过来比较顺手 反转后的a[0]=反转前的a[n],以此类推直 ... 
- java 解决JFrame不能设置背景色的问题                                                    分类:            Java Game             2014-08-15 09:48    119人阅读    评论(0)    收藏
			这段时间比较多,于是写一写JAVA的一些IT技术文章.如有JAVA高手请加QQ:314783246,互相讨论. 在Java的GUI设计中,Frame和JFrame两者之间有很大差别,上次刚学时编一个窗 ... 
- skinned mesh 蜘蛛样
			被skinned mesh 折磨了 好久,开始感觉skinindices不对,因为pix显示里面全是0 后来跟来跟去发现是这样的,那些uchar的整数被pix用float的格式显示出来 (显示为0.0 ... 
- centos使用更新更快的yum源
			The Remi Repo is a yum repository maintained by a French dude - Remi Collet. It contains much more u ... 
- vs2008 添加与修改模板.
			添加 我的模板: 路径: C:\Users\Administrator\Documents\Visual Studio 2008\Templates\ItemTemplates\Visual C# ... 
