2014-09-01 109 views
-2

在遍历列表时,可能会删除项目。迭代时从列表中删除项目

private void removeMethod(Object remObj){ 
    Iterator<?> it = list.iterator(); 
    while (it.hasNext()) { 
     Object curObj= it.next(); 
     if (curObj == remObj) { 
      it.remove(); 
      break; 
     } 
    } 
} 

当上面的代码可能发生在另一个循环中时,会发生问题,该循环正在主动迭代原始列表。

private void performChecks(){ 
    for(Object obj : list){ 
     //perform series of checks, which could result in removeMethod 
     //being called on a different object in the list, not the current one 
    } 
} 

如何从遍历列表中删除未知对象?

我有侦听的对象的列表。在通知事件的听众时,可能不再需要其他听众。

+1

您是否尝试过使用增强for循环和.remove()方法?和一个同步类? – arielnmz 2014-09-01 23:25:48

+1

你的问题不清楚给我。任何例子? – 2014-09-01 23:27:19

+1

removeMethod的加强for循环?这会抛出[ConcurrencyModificationExceptionError](http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html) – 2014-09-01 23:27:20

回答

0

如果我正确理解你的问题,以下是可能的解决方案(可能不是最有效的,但我认为是值得一试):每次:

在performChecks()使用for(Object obj : list.toArray())

优势该列表被“刷新”到数组中,它将反映这些变化。 因此,如果项目从单独的循环中的列表中删除

0

您的问题有点混乱,所以我会回答我认为我理解的东西;你的问题是这样的:如何从列表中删除一个项目,同时迭代列表并删除项目或如何避免ConcurrentModificationException

首先,代码中的问题是您使用迭代器而不是列表来移除项目。其次,如果你使用的并发性,使用CopyOnWriteArrayList

list.remove()

提供场景一个很好的例子删除的项,检查this

所以这是不好:

List<String> myList = new ArrayList<String>(); 

    myList.add("1"); 
    myList.add("2"); 
    myList.add("3"); 
    myList.add("4"); 
    myList.add("5"); 

    Iterator<String> it = myList.iterator(); 
    while(it.hasNext()){ 
     String value = it.next(); 
     System.out.println("List Value:"+value); 
     if(value.equals("3")) myList.remove(value); 
    } 

,这是很好的:

List<String> myList = new CopyOnWriteArrayList<String>(); 

    myList.add("1"); 
    myList.add("2"); 
    myList.add("3"); 
    myList.add("4"); 
    myList.add("5"); 

    Iterator<String> it = myList.iterator(); 
    while(it.hasNext()){ 
     String value = it.next(); 
     System.out.println("List Value:"+value); 
     if(value.equals("3")){ 
      myList.remove("4"); 
      myList.add("6"); 
      myList.add("7"); 
     } 
    } 
    System.out.println("List Size:"+myList.size());