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

Figure 4. Run of GoodLayeredPane

In summary, the key pitfall in our JLayeredPane example is the incorrect assumption that the JLayeredPane has a default LayoutManager, as JFrame and JPanel do. Experience tells us to eliminate that assumption and position and size the components for each layer. Once we do so, the JLayeredPane works fine.

Pitfall 10: How not to visit a Vector

Reader Win Harrington noticed a pitfall in the Enumeration implementation class, where its behavior differs from Iterator (both visit each element in a collection). Listing 10.1 demonstrates the behavior in question by removing an element while it iterates over the collection:

Listing 10.1. BadVisitor.java

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


When run, Listing 10.1 produces the following output:

  • Print
  • Feedback

Resources