Search code examples
javacomparable

Correct it so that it will compile and properly implement Comparable


Why won't the following program compile? Correct it so that it will compile and properly implement Comparable.

class Int implements Comparable
{
    private int x;
    public Int(int x)
    {
        this.x = x;
    }
    public int compareTo(Int other)
    {
        return x - other.x;
    }
}

----//// im assuming that the compareTo method is wrong.. but i dont know why or how to fix it.


Solution

  • The interface Comparable is defined with a type parameter of <T>.

    If one does not provide a generic type parameter to a class or interface that requires it, then the default type parameter is assumed to be Object.

    So, in effect, your class declaration reads like this:

    public class Int implements Comparable<Object>
    

    Now, this is where things get interesting. compareTo(T other) takes the generic type parameter as its type argument. If you don't explicitly declare the type to be something, then the method signature reads compareTo(Object other).

    Suffice to say, but Object and Int aren't the same object. When you attempt to declare your method as @Override, the compiler will inform you that your method doesn't inherit or implement anything.

    Ultimately, what this boils down to: you have to fix your type parameter. If you want to compare against Int, explicitly declare it so:

    public class Int implements Comparable<Int>
    

    Now, your code will compile.