Return to lecture notes index

15-100 Lecture 16 (Monday, October 9, 2006)

Today's Quiz

  
class Apple {

  private String color;
  private int weightOz;
 
  
  public Apple (String color, int weightOz) {
    this.color = color;
    this.weightOz = weightOz;
  }
 
  
  public String getColor() {
    return color;
  }
 
  
  public int getWeightOz() {
    return weightOz;
  }


  // QUESTION 1
  // Add the magic foo that allows apples this apple to determine if it
  // is equivalent to another (in the standard way)
  
  public boolean equals (Object o) {
    Apple a = (Apple) o;
    
    if (!color.equals(a.color))
      return false;
      
    if (weightOz != a.weigthOz)
      return false;
  
    return true;
  }

  // QUESTION 2
  // Add the magic foo that allows the apple to be converted into a String
  // ...also in the standard way  
  
  public String toString() {
  
    return color + ", " + weightOz + " oz";
  
  }
  

  public static void main (String[] args) {
  
    // QUESTION 3
    // Create two apples
    Apple a1 = new Apple ("red", 4);
    Apple a2 = new Apple ("green", 3);
    
    // Compare them
    if (a1.equals(a2)) 
      System.out.println ("Equivalent");
    

    // Print each one out separately
    System.out.println (a1);
    System.out.println (a2);  
  }

}

  

The Comparable Interface

Java defines an interface, Comparable, as follows:

  interface Comparable {
    public int compareTo(Object o);
  }
  

This interface provides a uniform way to Compare implementing Objects, known as Comparables. An Object implements Comparable by doing the following:

Let's take a look at an example compareTo method for our Apple class. We'll compare them by their weight.

  public int compareTo(Object o) {
    Apple a  = (Apple) o;
    
    int difference = this.color.compareTo(a.color);
  
    if (difference != 0)
      return difference;
      
    return (this.weigthOz - a.weightOz);
  
  }