Let's say I have a Set of Integers, and I want to increment every Integer in the Set. How would I do this?
Am I allowed to add and remove elements from the set while iterating it?
Would I need to create a new set that I would "copy and modify" the elements into, while I'm iterating the original set?
EDIT: What if the elements of the set are immutable?
You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().
Example 2: Iterate through Set using iterator() We have used the iterator() method to iterate over the set. Here, hasNext() - returns true if there is next element in the set. next() - returns the next element of the set.
Even though java. util. ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.
It is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.
You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().
however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.
Set<Integer> s; //contains your Integers ... Set<Integer> temp = new Set<Integer>(); for(Integer i : s) temp.add(i+1); s.clear(); s.addAll(temp);
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