Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete element oh HashSet inside for

Tags:

java

hashset

i want to 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 are an error java.util.ConcurrentModificationException how can I delete an element of a set during a parcour ?

like image 532
Mehdi Avatar asked Feb 22 '23 15:02

Mehdi


2 Answers

Instead of using the modified for loop, you can use an Iterator. Iterators have a remove method that lets you 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();
    }
}
like image 188
Jack Edmonds Avatar answered Mar 08 '23 14:03

Jack Edmonds


Read the javadoc:

The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException.

Use an Iterator and its remove() method.

MyClass edg
Iterator<MyClass> hashItr = myHashSet.iterator();
while ( hashItr.hasNext() ) {
    edge = hashItr.next();
    if ( . . . )
        hashItr.remove();
}
like image 30
texclayton Avatar answered Mar 08 '23 12:03

texclayton