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:
- Adding the "implements Comparable" clause, as in "class BusinessCard implements Comparable"
- Defining a matching method.
- By convention (not enforced by Java), implementing the method so that its logical results are as follows: x.compareTo(y) has a meaning similar to (x - y). If x.equals(y), it returns 0. If (x > y), it returns a positive number. If (x < y), it returns a negative number.
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); }