/* * A very simple example of implementing the comparable interface * The class below implements a Rectangle that is comparable with * other rectangles by its area. * * @author gtowell * created: August 6, 2021 */ public class CompExRect implements Comparable { // the width and height -- may not be changed and must be set private final int width, height; // Constructor to set the width and height public CompExRect(int w, int h) { width = w; height = h; } /* * The Area * @return the area */ public int area() { return width * height; } @Override public int compareTo(CompExRect cer) { // Just subtract one area from the other //compareTo only care about the sign of the result, not the magnitude if (cer == null) return 1; // annoyingly, null can sneak in here so it needs to be handled return this.area() - cer.area(); } @Override public String toString() { return "<>"; } public static void main(String[] args) { // Array of objects to be compared // Watch out for null CompExRect[] ce = { new CompExRect(3,4), new CompExRect(5, 2), new CompExRect(11, 1), new CompExRect(1, 7), null }; for (int i = 0; i < ce.length - 1; i++) { for (int j = i + 1; j < ce.length; j++) { System.out.println(ce[i] + " " + ce[j] + " " + ce[i].compareTo(ce[j])); } } //The next line will not compile as compareTo is only defined for comparing this class //System.out.println(ce[0].compareTo("cer")); } }