/*
 * Cart.java
 * Created on December 4, 2002
 */

package collections.sortable;

import java.util.*;

/**
 * Demonstrates the use of comparable objects and explicit comparators
 * used for sorting. Objects are added to a HashSet (which is faster)
 * and then passed into a new TreeSet (which supports sorting).
 * @author  Thomas Rowland
 */
public class Cart {

  public static void main(String[] args) {
    Cart cart = new Cart();
    Set hs = new HashSet();

    //add some products
    hs.add(new SortableProduct(88888, "Lawn Mower", "24inch, reverse, side attachment", 1, 249.99));
    hs.add(new SortableProduct(22222, "Baseball Glove", "Tom Seaver autographed", 3, 595));
    hs.add(new SortableProduct(77777, "Pencil", "No.8 mechanical", 100, 4.50));
    hs.add(new SortableProduct(99999, "Pencil", "No.2", 500, .15));
    hs.add(new SortableProduct(33333, "Eraser", "Ergonomic", 200, .35));
    hs.add(new SortableProduct(77777, "Pencil", "No.8 mechanical", 999, 4.50)); // add fails

    //sort 3 different ways
    cart.sort(hs);
    cart.sort(hs, SortableProduct.PRICE_COMPARATOR);
    cart.sort(hs, SortableProduct.QTY_COMPARATOR);
  }

  public void retrieve(Set s) {
    Iterator i = s.iterator();
    while (i.hasNext()) {
      System.out.println(((SortableProduct) i.next()).toString());
    }
  }

  /**
   * Sorts a set (a TreeSet) according to the objects' natural ordering
   * defined by its conmpareTo method.
   */
  public void sort(Set set) {
    System.out.println("\n*** Hashset to treeset - natural ***");
    TreeSet sortedSet = new TreeSet(set);
    retrieve(sortedSet);
  }

  /**
   * Sorts a set (a TreeSet) according to the eplicit Comparator.
   */
  public void sort(Set set, Comparator comparator) {
    System.out.println("\n*** Hashset to treeset - "
                       + comparator.getClass() + "***");
    TreeSet sortedSet = new TreeSet(comparator);
    sortedSet.addAll(set);
    retrieve(sortedSet);
  }
}