I have a problem with Sets/Iterators in Java. I'm executing code that iterates over elements in a hash set, removing them after they have been used but also removing elements that have been deemed unnecessary to iterate over within the loop. I'm also adding elements to the loop. Here's a code sample:
Set<Integer> thisSet = new HashSet<Integer>();
// add elements into set
while (!thisSet.isEmpty()) {
int value = thisSet.iterator().next();
thisSet.remove(value);
// more remove and add operations
}
I chose hash sets because I thought that the remove operations during the loop would be a lot faster than when using a list. The problem is that statistics show me that if the set gets large, polling a value from the set actually takes up a lot of time (I assume due to creating an iterator every time?). Does anyone have suggestions on how to improve this?
Thanks!