public class ComplexTest { 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); System.out.println(c1.compareTo(c2)); } 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 double real; private double complex; public Complex(double real, double 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 o) { Complex c = (Complex)o; if (mag(this) < mag(c)) return -1; else if (mag(this) > mag(c)) return 1; return 0; } private double mag(Complex c) { double asqu = c.real*c.real; double bsqu = c.complex*c.complex; return Math.sqrt(asqu+bsqu); } }