interface MyComparable { public int compareTo(Object o); } // Must use java.lang.Comparable in order for this to work with Arrays.sort. class Rectangle implements Comparable { private int length; private int width; public Rectangle(int length, int width) { this.width = width; this.length = length; } public int compareTo(Object o) { Rectangle r2 = (Rectangle)o; int r2Area = r2.length * r2.width; int myArea = length * width; if (myArea > r2Area) { return 1; } else if (myArea < r2Area) { return -1; } else { return 0; } } public String toString() { return "Rectangle with length: " + length + " and width: " + width; } } public class ComparableDriver { public static void main(String[] args) { Rectangle r1 = new Rectangle(5, 6); Rectangle r2 = new Rectangle(3, 4); Rectangle r3 = new Rectangle(6, 5); Rectangle r4 = new Rectangle(1, 2); System.out.println("Rectangle r1 compared to r2: " + r1.compareTo(r2)); System.out.println("Rectangle r1 compared to r3: " + r1.compareTo(r3)); Rectangle[] rectArray = new Rectangle[] {r1, r2, r3, r4}; java.util.Arrays.sort(rectArray); for (int i = 0; i < rectArray.length; i++) { System.out.println(rectArray[i]); } } }