001package edu.pdx.cs410J.core;
002
003import java.util.*;
004
005/**
006 * This class represents a box of cereal.  It has a name and a price.
007 */
008public class Cereal implements Comparable<Cereal> {
009  private String name;
010  private double price;
011
012  /**
013   * Creates a new box of cereal
014   */
015  public Cereal(String name, double price) {
016    this.name = name;
017    this.price = price;
018  }
019
020  /**
021   * Returns the name of this cereal
022   */
023  public String getName() {
024    return this.name;
025  }
026
027  /**
028   * Returns the price of this cereal
029   */
030  public double getPrice() {
031    return this.price;
032  }
033
034  public String toString() {
035    return this.name + " $" + this.price;
036  }
037
038  /**
039   * Compares two <code>Cereal</code>s based on their name
040   */
041  public int compareTo(Cereal c2) {
042    return this.getName().compareTo(c2.getName());
043  }
044
045  /**
046   * Two be consistent with the natural ordering, two
047   * <code>Cereal</code>s that have the same name, are themselves the
048   * same.
049   */
050  public boolean equals(Object o) {
051    if (o instanceof Cereal) {
052      Cereal other = (Cereal) o;
053      return this.getName().equals(other.getName());
054    }
055    return false;
056  }
057
058  /**
059   * Two cereals that are equal must have the same hash code.
060   */
061  public int hashCode() {
062    return this.getName().hashCode();
063  }
064
065  /**
066   * Demonstrates the natural ordering of <code>Cereals</code> by
067   * adding a bunch of cereals to a {@link SortedSet}
068   */
069  public static void main(String[] args) {
070    SortedSet<Cereal> set = new TreeSet<Cereal>();
071    set.add(new Cereal("Total", 3.56));
072    set.add(new Cereal("Raisin Bran", 2.65));
073    set.add(new Cereal("Sugar Crisps", 2.38));
074
075    for (Cereal c : set ) {
076      System.out.println(c);
077    }
078  }
079
080}