代码改变世界

Java中如何循环删除一个集合(如List)中的多个元素

2011-08-04 16:20  myjava2  阅读(335)  评论(0编辑  收藏  举报
 今天我需要从一个java的集合中,根据另一个集合的内容,删除第一个集合中不特定的元素。这看上去非常简单,但却遇到了问题。这就是“Java中如何删除一个集合中的多个元素”的问题。
这是我要写的方法的头部
private void screenBlackNameList(List<SharedBoardSmsWrapper> source, List<BlackNameListModel> blackNameList)

事情是这样子的。source集合中保存了一些显示用的数据元素。blackNameList集合中保存的是黑名单列表。我们需要根据黑名单表,把source集合中黑名单用户的数据剔除掉。

这个问题的解决看上去非常简单。

我首先使用for each 语句进行删除。
Java代码
  1. for(SharedBoardSmsWrapper tmpSharedBoardSmsWrapper:source){  
  2.           
  3.         for(BlackNameListModel tmpBlackNameListModel:blackNameList){  
  4.             if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){  
  5.                source.remove(tmpSharedBoardSmsWrapper);  
  6.                break;  
  7.             }  
  8.               
  9.         }  
  10.     }  

非常简单的问题!我暗笑,
测试…
令我意外的是,这段代码居然抛出了异常
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循环了!
Java代码
  1. for(int i=0;i<source.size();i++){  
  2.         SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=source.get(i);  
  3.         for(int j=0;j<blackNameList.size();j++){  
  4.             BlackNameListModel tmpBlackNameListModel=blackNameList.get(j);  
  5.             if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){  
  6.                source.remove(tmpSharedBoardSmsWrapper);  
  7.                break;  
  8.             }  
  9.         }  
  10.     }  

这下应该没问题了吧!信心满满地按下测试…
晕!怎么回事,数据怎么过滤得不对?

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 方法。
Java代码
  1. /** 
  2.      *@paramsource 
  3.      *@paramblackNameList 
  4.      */  
  5.     privatevoid screenBlackNameList(List<SharedBoardSmsWrapper> source, List<BlackNameListModel> blackNameList){  
  6.     Iterator<SharedBoardSmsWrapper> sourceIt=source.iterator();  
  7.       
  8.     while(sourceIt.hasNext()){  
  9.         SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=sourceIt.next();  
  10.         Iterator<BlackNameListModel> blackNameListIt=blackNameList.iterator();  
  11.         while(blackNameListIt.hasNext()){  
  12.             BlackNameListModel tmpBlackNameListModel=blackNameListIt.next();  
  13.            if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){  
  14.                sourceIt.remove();  
  15.                break;  
  16.             }  
  17.         }  
  18.     }  
  19.     }  

注意,一次Iterator的next()方法,不能多次调用remove()方法。否则会抛出异常。

看来,删除集合中的元素,最简单的方法,就是使用Iterator的remove()方法了!
让我们看看ArrayList类提供的Iterator是怎样实现的。
Java代码
  1. privateclass Itr implements Iterator<E> {  
  2.     /** 
  3. 这是元素的索引,相当于一个指针,或者游标,利用它来访问List的数据元素。 
  4.      *Indexofelementtobereturnedbysubsequentcalltonext. 
  5.      */  
  6.     intcursor = 0;  
  7.   
  8.     /** 
  9.      *Indexofelementreturnedbymostrecentcalltonextor 
  10.      *previous. Resetto-1ifthiselementisdeletedbyacall 
  11.      *toremove. 
  12. 最新元素的索引。如果已经删除了该元素,就设为-1 
  13.      */  
  14.     intlastRet = -1;  
  15.   
  16.     /** 
  17. 外部类ArrayList的属性: 
  18. protected transient int modCount = 0; 
  19.     它用于观察ArrayList是否同时在被其他线程修改,如果不一致,那么就会抛出同步异常。 
  20.      *ThemodCountvaluethattheiteratorbelievesthatthebacking 
  21.      *Listshouldhave. Ifthisexpectationisviolated,theiterator 
  22.      *hasdetectedconcurrentmodification. 
  23.      */  
  24.     intexpectedModCount = modCount;  
  25. //如果游标没有达到List的尺寸,那么就还有元素。  
  26.     publicboolean hasNext() {  
  27.             returncursor != size();  
  28.     }  
  29. //返回当前元素,然后游标+1。最近索引 也= 返回的元素的索引。  
  30.     public E next() {  
  31.             checkForComodification();  
  32.         try {  
  33.        E next = get(cursor);  
  34.        lastRet = cursor++;  
  35.        return next;  
  36.         } catch (IndexOutOfBoundsException e) {  
  37.        checkForComodification();  
  38.        thrownew NoSuchElementException();  
  39.         }  
  40.     }  
  41. /* 
  42. 删除元素,就是删除当前元素,并且把游标-1。因为,List会把后面的元素全部移前一位。 
  43. */  
  44.     publicvoid remove() {  
  45.         if (lastRet == -1)  
  46.        thrownew IllegalStateException();  
  47.             checkForComodification();  
  48.   
  49.         try {  
  50.        AbstractList.this.remove(lastRet);  
  51.        if (lastRet < cursor)  
  52.            cursor--;  
  53.        lastRet = -1;  
  54.        expectedModCount = modCount;  
  55.         } catch (IndexOutOfBoundsException e) {  
  56.        thrownew ConcurrentModificationException();  
  57.         }  
  58.     }  
  59.   
  60.     finalvoid checkForComodification() {  
  61.         if (modCount != expectedModCount)  
  62.        thrownew ConcurrentModificationException();  
  63.     }  
  64.     }  

可以看到,Iterator删除了元素,并且把游标重新置为正确的位子。只要没有其他线程同时改变该集合,就不会有任何问题。

以下使自己写得一小段代码,分了三种情况进行说明:
Java代码
  1. package com.iss;  
  2. import java.util.ArrayList;  
  3. import java.util.Iterator;  
  4. import java.util.List;  
  5. public class Test  
  6. {  
  7.     /** 
  8.      * @param args 
  9.      */  
  10.     public static void main(String[] args)  
  11.     {  
  12.         // TODO Auto-generated method stub  
  13.         List<String> list = new ArrayList();  
  14.           
  15.         for(int i = 0; i<10; i++)  
  16.         {  
  17.             list.add("This is" + i);  
  18.         }  
  19.         System.out.println("hello");  
  20.           
  21.         list.remove("This is1");  
  22.           
  23.         for(Iterator iter = list.iterator(); iter.hasNext(); )  
  24.         {  
  25.             String str = (String) iter.next();  
  26.             if(str.indexOf("1") != -1)  
  27.             {  
  28.                 //情况一  
  29.                 iter.remove();  
  30.                 //情况二  
  31.                 list.remove(str);  
  32.             }  
  33.         }  
  34.           
  35.         //情况三  
  36.         for(String strs : list)  
  37.         {  
  38.             if(strs.indexOf("1") != -1)  
  39.             {  
  40.                 list.remove(strs);  
  41.                 System.out.println(strs);  
  42.             }  
  43.         }  
  44.           
  45.         for(String strT : list)  
  46.         {  
  47.             System.out.println(strT);  
  48.         }  
  49.     }  
  50. }  

这三种中只有一种有用,你可以试一试!