I am having trouble using Iterator in java.
it=myHash.iterator();
while (it.hasNext())
if (it.next() satisfying something)
do something
while (it.hasNext())
if (it.next() satisfying something)
it.remove();
I am trying to iterate hashset twice, and the first loop making it.hasNext() return false. How to i resolve this?
I tried even adding the edit as you guys suggested, still not working…
You’re reusing the same iterator – and that’s been invalidated by adding new items to the set.
You should call
iterator()again on the set:You can’t reset the existing iterator
EDIT: Here’s some sample code which shows this working:
This gives the results “new long text” and “food”.