Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Practice makes perfect

Experience is often your best defense against Java pitfalls

  • Print
  • Feedback

Page 5 of 9

Now let's examine the correct way to remove an item while iterating. Listing 10.3 demonstrates both visiting and modifying with an Iterator:

Listing 10.3. GoodVisitor.java

package com.javaworld.jpitfalls.article5;
import java.util.*;
public class GoodVisitor
{
    public static void main(String args[])
    {
        Vector v = new Vector();
        v.add("one"); v.add("two"); v.add("three"); v.add("four");
        
        Iterator iter = v.iterator();
        while (iter.hasNext())
        {
            String s = (String) iter.next();
            if (s.equals("two"))
                iter.remove();
            else
            {
                // Visit
                System.out.println(s);
            }
        }
                
        // See what's left
        System.out.println("What's really there...");
        iter = v.iterator();
        while (iter.hasNext())
        {
            String s = (String) iter.next();
            System.out.println(s);            
        }
    }    
}


When Listing 10.3 runs, it produces the following output:

  • Print
  • Feedback

Resources