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

1    /* 
2     * Cart.java 
3     * Created on December 4, 2002 
4     */ 
5     
6    package collections.sortable; 
7     
8    import java.util.*; 
9     
10   /** 
11    * Demonstrates the use of comparable objects and explicit comparators 
12    * used for sorting. Objects are added to a HashSet (which is faster) 
13    * and then passed into a new TreeSet (which supports sorting). 
14    * @author  Thomas Rowland 
15    */ 
16   public class Cart { 
17    
18       public static void main(String[] args) { 
19           Cart cart = new Cart(); 
20           Set hs = new HashSet(); 
21    
22           //add some products 
23           hs.add(new SortableProduct(88888, "Lawn Mower", "24inch, reverse, side attachment", 1, 249.99)); 
24           hs.add(new SortableProduct(22222, "Baseball Glove", "Tom Seaver autographed", 3, 595)); 
25           hs.add(new SortableProduct(77777, "Pencil", "No.8 mechanical", 100, 4.50)); 
26           hs.add(new SortableProduct(99999, "Pencil", "No.2", 500, .15)); 
27           hs.add(new SortableProduct(33333, "Eraser", "Ergonomic", 200, .35)); 
28           hs.add(new SortableProduct(77777, "Pencil", "No.8 mechanical", 999, 4.50)); // add fails 
29    
30           //sort 3 different ways 
31           cart.sort(hs); 
32           cart.sort(hs, SortableProduct.PRICE_COMPARATOR); 
33           cart.sort(hs, SortableProduct.QTY_COMPARATOR); 
34       } 
35    
36       public void retrieve(Set s) { 
37           Iterator i = s.iterator(); 
38           while (i.hasNext()) { 
39               System.out.println(((SortableProduct) i.next()).toString()); 
40           } 
41       } 
42    
43       /** 
44        * Sorts a set (a TreeSet) according to the objects' natural ordering 
45        * defined by its conmpareTo method. 
46        */ 
47       public void sort(Set set) { 
48           System.out.println("\n*** Hashset to treeset - natural ***"); 
49           TreeSet sortedSet = new TreeSet(set); 
50           retrieve(sortedSet); 
51       } 
52    
53       /** 
54        * Sorts a set (a TreeSet) according to the eplicit Comparator. 
55        */ 
56       public void sort(Set set, Comparator comparator) { 
57           System.out.println("\n*** Hashset to treeset - " 
58                   + comparator.getClass() + "***"); 
59           TreeSet sortedSet = new TreeSet(comparator); 
60           sortedSet.addAll(set); 
61           retrieve(sortedSet); 
62       } 
63   } 
64