Interface java.lang.Comparable

Interfaces are used frequently in the Java run-time library. Here is the source of interface Comparable in the java.lang package up to JDK 1.4. (We'll show the JDK 1.5 code, which is different, soon).

public interface Comparable {
   public int compareTo(Object o);
}

All classes that implement Comparable have to provide a compareTo() method. It allows two objects of the same class to be put in order with respect to one another, that is, they can be compared.

If you read the API documentation, you will see that implementations of compareTo() must return a negative, zero, or positive int, depending on whether “this” is smaller, equal to, or greater than the object parameter. There isn't any way for the compiler to enforce this level of meaning, and if you make compareTo() do anything different for one of your classes, this code will be broken anywhere you use that class in place of a Comparable.

Here's a complete example that implements the Comparable interface. To keep it simple, the example is a class that “wraps” an int as an object.

class MyInt implements Comparable {
    private int mi;
    public MyInt(int i) { mi = i; }      // constructor
    public int getMyInt() { return mi; } // getter

    public int compareTo(Object other) {
        MyInt miOther = (MyInt) other;   //cast Obj param back to MyInt
        return (this.mi - miOther.mi);
    }
 }

You can declare MyInts and compare them like this:

MyInt m4 = new MyInt(4);
MyInt m5 = new MyInt(5);

int result = m4.compareTo(m5);  // negative, zero or positive

That's the way Comparable looked before JDK 1.5. In JDK 1.5, classes and interfaces are allowed to take generic parameters, and Comparable was changed for that.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.142.232