public class Compare { public static void main(String[] args) { Comparable c1 = randomComplex(1,3); Comparable c2 = randomComplex(1,3); System.out.println("C1: " + c1); System.out.println("C2: " + c2); switch(c1.compareTo(c2)) { case -1: System.out.println("less!"); break; case 0: System.out.println("same!"); break; case 1: System.out.println("more!"); break; case 9999: System.out.println("buh?"); break; default: System.out.println("uh oh!"); } } private static Complex randomComplex(int x, int y) { return new Complex(myRandom(x,y),myRandom(x,y)); } private static int myRandom(int min, int max) { return (int) (Math.random()*(max-min+1)) + min; } } class Complex implements Comparable { private int real; private int complex; public Complex(int real, int complex) { this.real = real; this.complex = complex; } public String toString() { String op="+"; if(complex<0) op=""; return real+op+complex+"i"; } public boolean equals(Complex c) { return complex==c.complex && real==c.real && mag(this)==mag(c); } public int compareTo(Object c) { int result=9999; if (mag(this) < mag((Complex)c)) result=-1; else if (this.equals((Complex)c)) result=0; else if (mag(this) > mag((Complex)c)) result=1; return result; } private double mag(Complex c) { double asqu = c.real*c.real; double bsqu = c.complex*c.complex; return Math.sqrt(asqu+bsqu); } }