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 3 of 9

E:\classes\com\javaworld\jpitfalls\article5>java com.javaworld.jpitfalls.article5.BadVisitor
one
four
What's really there...
one
three
four


We expect to have visited elements one, three, and four, but instead we receive only visited elements one and four. The problem: We assume the Enumeration implementation and the Vector class work in sync; that is not the case. The Vector.remove() method goes against our expectations; it doesn't modify the index integer (called count).

Listing 10.2 demonstrates how an Iterator removes an item while iterating:

Listing 10.2. BadVisitor2.java

package com.javaworld.jpitfalls.article5;
import java.util.*;
public class BadVisitor2
{
    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"))
                v.remove("two");
            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 run, Listing 10.2 produces the following output:

  • Print
  • Feedback

Resources