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

1    /* 
2     * Product.java 
3     * 
4     * Created on December 3, 2002 
5     */ 
6     
7    package collections.hashset; 
8     
9    /** 
10    * Demonstrates how to override the hashCode and equals 
11    * methods to test for equality. 
12    * 
13    * @author  Thomas Rowland 
14    */ 
15   public class Product { 
16       private int id;     // unique 
17       private String name; 
18       private String descr; 
19       private int qty; 
20       private double priceEa; 
21       private double priceNet; 
22    
23       public Product(int _id, String _name, 
24                      String _descr, int _qty, double _price) { 
25           id = _id; 
26           name = _name; 
27           descr = _descr; 
28           qty = _qty; 
29           priceEa = _price; 
30           priceNet = qty * priceEa; 
31       } 
32    
33       /** 
34        * Overridden hashCode method. This method gets called first when 
35        * this object is being added or removed from the HashSet. 
36        */ 
37       public int hashCode() { 
38           System.out.println("-- hashCode method called."); 
39           return id; 
40       } 
41    
42       /** 
43        * Overridden equals method. This method gets called when 
44        * the hash codes from both objects being compared are equal. 
45        */ 
46       public boolean equals(Object o) { 
47           System.out.println("-- equals method called."); 
48           if (o != null && o.getClass().equals(this.getClass())) 
49               return (id == ((Product) o).getId()); 
50           return false; 
51       } 
52    
53       public String toString() { 
54           return "\nid:" + id + 
55                   "\nname=" + name + 
56                   "\ndescr=" + descr + 
57                   "\nqty=" + qty + 
58                   "\npriceEach=" + priceEa + 
59                   "\npriceNet=" + priceNet; 
60       } 
61    
62       public int getId() { 
63           return id; 
64       } 
65    
66       public String getName() { 
67           return name; 
68       } 
69    
70       public String getDescr() { 
71           return descr; 
72       } 
73    
74       public int getQty() { 
75           return qty; 
76       } 
77    
78       public double getPriceEa() { 
79           return priceEa; 
80       } 
81    
82       public double getPriceNet() { 
83           return priceNet; 
84       } 
85   }