• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 196
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

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