Delete element oh HashSet inside for

I want through a HashSet with for (MyClass edg : myHashSet) and inside for , I want to delete an element for my HashSet.

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

but there is a java.util.ConcurrentModificationException error, how can I remove a set item during parcour?

+4
source share
3 answers

Instead of using a modified for loop, you can use Iterator . Iterators have a remove method that allows you to remove the last element returned by Iterator.next() .

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

Read javadoc:

The iterators returned by this class iterator method fail: if the set changes at any time after creating the iterator, in any way other than the iterator’s own deletion method, Iterator throws a ConcurrentModificationException.

Use Iterator and its remove () method.

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

I thought a bit, it has been a while since I made java, but another standard method of the swamp is:

 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
source

Source: https://habr.com/ru/post/1394643/


All Articles