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 ?
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();
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With