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

Posted on 2006-05-31
Last Modified: 2012-05-05
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);
     if (myObj.hasSomethingWrong())

Question by:BrianMc1958
    LVL 30

    Expert Comment

    It should be fine if you are using an Iterator.
    LVL 30

    Accepted Solution

    Or better try: iter.remove () ; // instead of myHashSet.remove ( myObj ) ;
    LVL 30

    Expert Comment

    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.
    LVL 30

    Expert Comment


    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    seriesUp challenge 7 81
    array11 challenge 16 40
    parentbit challenge 3 37
    for i loop in grovy 1 26
    An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
    Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
    Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
    This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

    731 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now