/Users/lyon/j4p/src/collections/hashset/Cart.java

1    /* 
2     * Cart.java 
3     * 
4     * Created on December 3, 2002 
5     */ 
6     
7    package collections.hashset; 
8     
9    import java.util.HashSet; 
10   import java.util.Iterator; 
11   import java.util.Set; 
12    
13   /** 
14    * Demonstrates adding Product objects that already exist in a 
15    * HashSet. The test for existence is based on the hashCode 
16    * and equals methods implemented in the Product class. 
17    * 
18    * @author  Thomas Rowland 
19    */ 
20   public class Cart { 
21    
22       private static Set products = new HashSet(); 
23    
24       public static void main(String[] args) { 
25           Cart cart = new Cart(); 
26           Product product; 
27    
28           //add a product to the cart 
29           product = new Product(1234, "Pasta", "Ziti, 16oz box", 3, 1.45); 
30           cart.addProduct(product); 
31    
32           //adding the same product again will fail 
33           product = new Product(1234, "Pasta", "Ziti, 16oz box", 1, 1.45); 
34           cart.addProduct(product); 
35    
36           //so it must first be removed then added 
37           cart.removeProduct(product); 
38           cart.addProduct(product); 
39    
40           //list the products 
41           Iterator iter = products.iterator(); 
42           while (iter.hasNext()) { 
43               System.out.println((Product) iter.next()); 
44           } 
45    
46       } 
47    
48       public void addProduct(Product product) { 
49           if (products.add(product)) 
50               System.out.println("New product added.\n"); 
51           else 
52               System.out.println("Product already exists!\n"); 
53       } 
54    
55       public void removeProduct(Product product) { 
56           if (products.remove(product)) 
57               System.out.println("Product removed.\n"); 
58           else 
59               System.out.println("Product not found!\n"); 
60       } 
61   } 
62