• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 192
  • Last Modified:

Can I safely iterate, and delete from, a List?

Dear Experts,

While I'm iterating a HashSet, can I safely delete from that HashSet within the same loop?  Or should I "mark" them somehow, and delete them later?  Code example:

Iterator iter = myHashSet.iterator();
while (iter.hasNext())
  {
     myObj = (MyObj) iter.next();
     if (myObj.hasSomethingWrong())
         myHashSet.remove(myObj);
   }
      

Thanks,
BrianMc1958
0
BrianMc1958
Asked:
BrianMc1958
  • 4
1 Solution
 
Mayank SAssociate Director - Product EngineeringCommented:
It should be fine if you are using an Iterator.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Or better try: iter.remove () ; // instead of myHashSet.remove ( myObj ) ;
0
 
Mayank SAssociate Director - Product EngineeringCommented:
If you were using an Enumeration you would've faced problems after deleting because it would've resulted in an invalid state, but with Iterator, deleting is an advantage.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
;-)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now