Java中如何循环删除一个集合(如List)中的多个元素
这是我要写的方法的头部
private void screenBlackNameList(List<SharedBoardSmsWrapper> source, List<BlackNameListModel> blackNameList)
事情是这样子的。source集合中保存了一些显示用的数据元素。blackNameList集合中保存的是黑名单列表。我们需要根据黑名单表,把source集合中黑名单用户的数据剔除掉。
这个问题的解决看上去非常简单。
我首先使用for each 语句进行删除。
- for(SharedBoardSmsWrapper tmpSharedBoardSmsWrapper:source){
- for(BlackNameListModel tmpBlackNameListModel:blackNameList){
- if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){
- source.remove(tmpSharedBoardSmsWrapper);
- break;
- }
- }
- }
for(SharedBoardSmsWrapper tmpSharedBoardSmsWrapper:source){ for(BlackNameListModel tmpBlackNameListModel:blackNameList){ if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){ source.remove(tmpSharedBoardSmsWrapper); break; } } }
非常简单的问题!我暗笑,
测试…
令我意外的是,这段代码居然抛出了异常
java.util.ConcurrentModificationException。
查看JDK6手册
public class ConcurrentModificationException
extends RuntimeException
当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。
例如,某个线程在 Collection 上进行迭代时,通常不允许另一个线性修改该 Collection。通常在这些情况下,迭代的结果是不确定的。如果检测到这种行为,一些迭代器实现(包括 JRE 提供的所有通用 collection 实现)可能选择抛出此异常。执行该操作的迭代器称为快速失败 迭代器,因为迭代器很快就完全失败,而不会冒着在将来某个时间任意发生不确定行为的风险。
注意,此异常不会始终指出对象已经由不同 线程并发修改。如果单线程发出违反对象协定的方法调用序列,则该对象可能抛出此异常。例如,如果线程使用快速失败迭代器在 collection 上迭代时直接修改该 collection,则迭代器将抛出此异常。
注意,迭代器的快速失败行为无法得到保证,因为一般来说,不可能对是否出现不同步并发修改做出任何硬性保证。快速失败操作会尽最大努力抛出 ConcurrentModificationException。因此,为提高此类操作的正确性而编写一个依赖于此异常的程序是错误的做法,正确做法 是:ConcurrentModificationException 应该仅用于检测 bug。
Java中的For each实际上使用的是iterator进行处理的。而iterator是不允许集合在iterator使用期间删除的。而我在for each时,从集合中删除了一个元素,这导致了iterator抛出了ConcurrentModificationException。
看来只有老老实实使用传统的for循环了!
- for(int i=0;i<source.size();i++){
- SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=source.get(i);
- for(int j=0;j<blackNameList.size();j++){
- BlackNameListModel tmpBlackNameListModel=blackNameList.get(j);
- if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){
- source.remove(tmpSharedBoardSmsWrapper);
- break;
- }
- }
- }
for(int i=0;i<source.size();i++){ SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=source.get(i); for(int j=0;j<blackNameList.size();j++){ BlackNameListModel tmpBlackNameListModel=blackNameList.get(j); if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){ source.remove(tmpSharedBoardSmsWrapper); break; } } }
这下应该没问题了吧!信心满满地按下测试…
晕!怎么回事,数据怎么过滤得不对?
Debug跟踪后发现,原来,集合删除元素时,集合的size会变小,连带索引都会改变!
这可怎么办?我不会被这样一个小问题搞得没辙了吧!
方法一:用传统for循环,从集合最后元素向前循环删除元素,集合的size会变小,连带索引都会改变,但不会影响到前面的未循环元素。
ArrayList<Integer> a=new ArrayList<Integer>(15);
a.add(222);
a.add(3);
a.add(333);
a.add(000);
a.add(333);
a.add(4);
for(int s=a.size()-1;s>=0;s--){
if(a.get(s).intValue()==333){
a.remove(s);
}
}
方法二:使用Iterator的remove()方法删除集合中的元素
查看JDK手册的Iterator接口,看到它还有一个remove方法。
remove
void remove()
从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作)。每次调用 next 只能调用一次此方法。如果进行迭代时用调用此方法之外的其他方式修改了该迭代器所指向的 collection,则迭代器的行为是不确定的。
抛出:
UnsupportedOperationException - 如果迭代器不支持 remove 操作。
IllegalStateException - 如果尚未调用 next 方法,或者在上一次调用 next 方法之后已经调用了 remove 方法。
- /**
- *@paramsource
- *@paramblackNameList
- */
- privatevoid screenBlackNameList(List<SharedBoardSmsWrapper> source, List<BlackNameListModel> blackNameList){
- Iterator<SharedBoardSmsWrapper> sourceIt=source.iterator();
- while(sourceIt.hasNext()){
- SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=sourceIt.next();
- Iterator<BlackNameListModel> blackNameListIt=blackNameList.iterator();
- while(blackNameListIt.hasNext()){
- BlackNameListModel tmpBlackNameListModel=blackNameListIt.next();
- if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){
- sourceIt.remove();
- break;
- }
- }
- }
- }
/** *@paramsource *@paramblackNameList */ privatevoid screenBlackNameList(List<SharedBoardSmsWrapper> source, List<BlackNameListModel> blackNameList){ Iterator<SharedBoardSmsWrapper> sourceIt=source.iterator(); while(sourceIt.hasNext()){ SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=sourceIt.next(); Iterator<BlackNameListModel> blackNameListIt=blackNameList.iterator(); while(blackNameListIt.hasNext()){ BlackNameListModel tmpBlackNameListModel=blackNameListIt.next(); if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){ sourceIt.remove(); break; } } } }
注意,一次Iterator的next()方法,不能多次调用remove()方法。否则会抛出异常。
看来,删除集合中的元素,最简单的方法,就是使用Iterator的remove()方法了!
让我们看看ArrayList类提供的Iterator是怎样实现的。
- privateclass Itr implements Iterator<E> {
- /**
- 这是元素的索引,相当于一个指针,或者游标,利用它来访问List的数据元素。
- *Indexofelementtobereturnedbysubsequentcalltonext.
- */
- intcursor = 0;
- /**
- *Indexofelementreturnedbymostrecentcalltonextor
- *previous. Resetto-1ifthiselementisdeletedbyacall
- *toremove.
- 最新元素的索引。如果已经删除了该元素,就设为-1
- */
- intlastRet = -1;
- /**
- 外部类ArrayList的属性:
- protected transient int modCount = 0;
- 它用于观察ArrayList是否同时在被其他线程修改,如果不一致,那么就会抛出同步异常。
- *ThemodCountvaluethattheiteratorbelievesthatthebacking
- *Listshouldhave. Ifthisexpectationisviolated,theiterator
- *hasdetectedconcurrentmodification.
- */
- intexpectedModCount = modCount;
- //如果游标没有达到List的尺寸,那么就还有元素。
- publicboolean hasNext() {
- returncursor != size();
- }
- //返回当前元素,然后游标+1。最近索引 也= 返回的元素的索引。
- public E next() {
- checkForComodification();
- try {
- E next = get(cursor);
- lastRet = cursor++;
- return next;
- } catch (IndexOutOfBoundsException e) {
- checkForComodification();
- thrownew NoSuchElementException();
- }
- }
- /*
- 删除元素,就是删除当前元素,并且把游标-1。因为,List会把后面的元素全部移前一位。
- */
- publicvoid remove() {
- if (lastRet == -1)
- thrownew IllegalStateException();
- checkForComodification();
- try {
- AbstractList.this.remove(lastRet);
- if (lastRet < cursor)
- cursor--;
- lastRet = -1;
- expectedModCount = modCount;
- } catch (IndexOutOfBoundsException e) {
- thrownew ConcurrentModificationException();
- }
- }
- finalvoid checkForComodification() {
- if (modCount != expectedModCount)
- thrownew ConcurrentModificationException();
- }
- }
privateclass Itr implements Iterator<E> { /** 这是元素的索引,相当于一个指针,或者游标,利用它来访问List的数据元素。 *Indexofelementtobereturnedbysubsequentcalltonext. */ intcursor = 0; /** *Indexofelementreturnedbymostrecentcalltonextor *previous. Resetto-1ifthiselementisdeletedbyacall *toremove. 最新元素的索引。如果已经删除了该元素,就设为-1 */ intlastRet = -1; /** 外部类ArrayList的属性: protected transient int modCount = 0; 它用于观察ArrayList是否同时在被其他线程修改,如果不一致,那么就会抛出同步异常。 *ThemodCountvaluethattheiteratorbelievesthatthebacking *Listshouldhave. Ifthisexpectationisviolated,theiterator *hasdetectedconcurrentmodification. */ intexpectedModCount = modCount; //如果游标没有达到List的尺寸,那么就还有元素。 publicboolean hasNext() { returncursor != size(); } //返回当前元素,然后游标+1。最近索引 也= 返回的元素的索引。 public E next() { checkForComodification(); try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); thrownew NoSuchElementException(); } } /* 删除元素,就是删除当前元素,并且把游标-1。因为,List会把后面的元素全部移前一位。 */ publicvoid remove() { if (lastRet == -1) thrownew IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { thrownew ConcurrentModificationException(); } } finalvoid checkForComodification() { if (modCount != expectedModCount) thrownew ConcurrentModificationException(); } }
可以看到,Iterator删除了元素,并且把游标重新置为正确的位子。只要没有其他线程同时改变该集合,就不会有任何问题。
以下使自己写得一小段代码,分了三种情况进行说明:
- package com.iss;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- public class Test
- {
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- // TODO Auto-generated method stub
- List<String> list = new ArrayList();
- for(int i = 0; i<10; i++)
- {
- list.add("This is" + i);
- }
- System.out.println("hello");
- list.remove("This is1");
- for(Iterator iter = list.iterator(); iter.hasNext(); )
- {
- String str = (String) iter.next();
- if(str.indexOf("1") != -1)
- {
- //情况一
- iter.remove();
- //情况二
- list.remove(str);
- }
- }
- //情况三
- for(String strs : list)
- {
- if(strs.indexOf("1") != -1)
- {
- list.remove(strs);
- System.out.println(strs);
- }
- }
- for(String strT : list)
- {
- System.out.println(strT);
- }
- }
- }
package com.iss; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub List<String> list = new ArrayList(); for(int i = 0; i<10; i++) { list.add("This is" + i); } System.out.println("hello"); list.remove("This is1"); for(Iterator iter = list.iterator(); iter.hasNext(); ) { String str = (String) iter.next(); if(str.indexOf("1") != -1) { //情况一 iter.remove(); //情况二 list.remove(str); } } //情况三 for(String strs : list) { if(strs.indexOf("1") != -1) { list.remove(strs); System.out.println(strs); } } for(String strT : list) { System.out.println(strT); } } }
这三种中只有一种有用,你可以试一试!
转载于:https://www.cnblogs.com/jpa2/archive/2011/08/04/2527559.html
Java中如何循环删除一个集合(如List)中的多个元素相关推荐
- 设计一个算法,删除一个单链表L中元素值最大的结点(假设最大值结点是唯一的)
设计一个算法,删除一个单链表L中元素值最大的结点(假设最大值结点是唯一的). #include <stdio.h> #include<malloc.h> typedef str ...
- 在MySQL中如何有效的删除一个大表?
在MySQL中如何有效的删除一个大表? Oracle大表的删除: http://blog.itpub.net/26736162/viewspace-2141248/ 在DROP TABLE 过程中,所 ...
- 汇编语言: 从键盘上输入一串字符(用回车键结束,使用 10 号功能调用。)放在 STRING 中,试 编制一个程序测试字符串中是否存在数字。如有,则把 CL 的第 5 位置 1,否则将该位置置 0。
从键盘上输入一串字符(用回车键结束,使用 10 号功能调用.)放在 STRING 中,试 编制一个程序测试字符串中是否存在数字.如有,则把 CL 的第 5 位置 1,否则将该位置置 0. data s ...
- join,和循环删除,fromkeys,集合,拷贝
一.对之知识点的补充. 1.str中join 方法.把列表转换成字符串 2.列表和字典在循环时不能直接删除. 需要把删除的内容记录在新列表中. 然后循环新列表.删除字典或列表 3.fromkeys() ...
- 循环删除List集合的错误
症状:不是郝柱也能看到灾备 分析:调试发现动作中有两个灾备,不过只过滤了其中一个 错误所在:代码如下,这里for循环删除List逻辑出问题了,犯了一个比较基础的错误 : 两个灾备动作索引是相邻的,当我 ...
- mysql中删除某一纵的方法_sql数据库:如何在一个表中填加或者删除一个字段!...
如要在一个hwsp表中填加字段:ylxs alter table hwsp add column ylxs ALTER TABLE 表 {ADD ADD{COLUMN 字段类型 [ (字长)] [NO ...
- 微信小程序中实现循环调用一个方法
要想循环调用一个方法肯定是要判断某个值,当这个值为假时调用这个方法,为真就不调用 query:function(){if(!!wx.getStorageSync('userInfo')){let _t ...
- python中for循环语句格式_关于Python中的for循环控制语句
#第一个:求 50 - 100 之间的质数 import math for i in range(50, 100 + 1): for j in range(2, int(math.sqrt(i)) + ...
- oracle数据存储过程 中的循环 for 拼接字符串,oracle存储过程中使用字符串拼接
1.使用拼接符号"||" v_sql := 'SELECT * FROM UserInfo WHERE ISDELETED = 0 AND ACCOUNT =''' || vAcc ...
最新文章
- python使用matplotlib对比多个模型的在训练集上的效果并使用柱状图进行可视化:基于交叉验证的性能均值(mean)和标准差(std)进行可视化分析、使用标准差信息添加误差区间条yerr
- MacBook Pro休眠掉电、耗电量大问题解决方案
- 单位阶跃信号是周期信号吗_手机信号变成“HD”,是代表没有信号吗?你的手机正在被扣费...
- Android工具HierarchyViewer 代码导读(3) -- 后台代码
- CentOS7 安装lua环境
- oracle 由32位迁移到64位的问题
- 学习python: x+=1 与 x = x + 1
- Winform解决界面重绘闪烁的问题
- ALPHACAM Desinger 2020.0中文破解版 64位
- 计算机科学与技术学科评估 第五轮,【学科评估】解读第五轮学科各学科评估变化(上)...
- Oracle中文转拼音函数
- el-form 表单的校验
- 《穹顶之下》全文整理
- 当Forms表单遇到Power BI
- 自动对焦模块理论基础及其硬件实现浅析(四)
- statis代码块以及非static代码块之执行
- flash迷宫游戏教程
- 基于Android的手机音乐播放器的设计
- Cool Edit Pro 常用快捷键
- SpringMVC @ResponseBody在IE8变下载