2012-02-03 41 views
4

我想通過HashSet與for (MyClass edg : myHashSet)和裏面for,我想刪除我的HashSet元素。刪除元素哦HashSet裏面爲

for (MyClass edg : myHashSet) 
{ 
    if(....) 
     myHashSet.remove(); 
} 

但有一個錯誤java.util.ConcurrentModificationException我怎麼能一個parcour中刪除集合中的元素?

+0

邁赫迪,如果有人已經回答了你的問題,這是件好事接受他們的答案,否則你會注意到人們開始不回答你的問題。 – 2012-03-22 10:35:58

回答

6

而不是使用修改的for循環,您可以使用Iterator。迭代器有一個remove方法,可以讓你刪除Iterator.next()返回的最後一個元素。

for (final java.util.Iterator<MyClass> itr = myHashSet.iterator(); itr.hasNext();) { 
    final MyClass current = itr.next(); 
    if(....) { 
     itr.remove(); 
    } 
} 
+0

但是,當我刪除一個迭代器的元素,它在我的Hashset中被刪除automaticaly? – Mehdi 2012-02-03 15:36:09

+2

@ user1149157是的。調用'Iterator.remove()'從HashSet中移除由'Iterator.next()'返回的最後一個項目。 – 2012-02-03 15:37:37

+0

Greaaaat ...謝謝youuuu – Mehdi 2012-02-03 15:39:06

2

閱讀的javadoc:

此類的iterator方法返回的迭代器是快速失敗的:如果集合隨時修改後的迭代器創建的,以任何方式,除了通過迭代器自己的remove方法,Iterator拋出一個ConcurrentModificationException異常。

使用Iterator及其remove()方法。

MyClass edg 
Iterator<MyClass> hashItr = myHashSet.iterator(); 
while (hashItr.hasNext()) { 
    edge = hashItr.next(); 
    if (. . .) 
     hashItr.remove(); 
} 
0

有一點一個想到的,已經有一段時間,因爲我做了Java,但要做到這一點另一個沼澤標準方法如下:

Set<Person> people = new HashSet<Person>(); 
Set<Person> peopleToRemove = new HashSet<Person>(); 

// fill the set of people here. 
for (Person currentPerson : people) { 
    removalSet.add(currentPerson); 
} 

people.removeAll(peopleToRemove); 
+0

另一種方法是使用Iterator.remove(),它避免了正常的ConcurrentModificationException,其中的一個例子可以在上面看到:) – 2012-03-22 10:34:16