The Comparable Interface -------------------------------- OK, when we talk about generic programming, we need to talk about the Comparable interface. This interface allows you to make generic classes that allow you to compare things. Here is the interface... Look up the spec in the API... interface Comparable { public int compareTo(Object compare); } Why is this useful? Well, sometimes we don't know how to compare objects. For example, how do we compare two complex numbers or how do we compare two people? It's really not that clear, and it's up to you to say person1 > person2 if person1 is taller than person2. This is the point of Comparable. Here is a dumbed down verstion of Schwartz's Complex class that was showed in class where complex numbers can be complared using their magnitudes... class Complex implements Comparable { public int real; public int complex; public Complex (int real, int complex) { this.real = real; this.complex = complex; } public int compareTo(Object o) { Complex compare = (Complex)o; double thisMagn = Math.sqrt(real*real + complex*complex); double compareMagn = Math.sqrt(compare.real*compare.real + compare.complex*compare.complex); if (thisMagn > compareMagn) return 1; else if (thisMagn == compareMagn) return 0; else return -1; } } Notice the compareTo() method returns 1 if the object is "larger" than the one passed in, 0 if they are "equal" and -1 if it is less than the one passed in. This interface will help you with generic programming. Let's see an application of the Comparable interface. Let's write a method that will return the "largest" element in an array of Objects. public Object max(Comparable[] list) { Comparable largest = list[0]; for (int i = 1; i < list.length; i++) { if (largest.compareTo(list[i]) == -1) //If largest < list[i] largest = list[i]; } return largest; } This is a basic method, but it is written in a very generic programming style. Why? Well, with my Complex object above, I can declare an array of Complex objects and have this max() method return the largest one, where "largest" is defined as how I defined it in compareto(). Complex[] list = new list[6]; //Initialize list... Complex largestMagn = (Complex) max(list); I could use the same method to find the largest integer... Integer[] list = new list[6]; //Initialize list... Integer largestMagn = (Integer) max(list); So, in conclusion, I have written one method, but I can pass in an array of anything as long as that anything implements Comparable.