Search code examples
javacomparable

Comparable interface using the compare method


Could anyone please explain me why the code below does not work:

public static void main(String[] args) throws IOException
 {
    Comparable<Integer> q = new Integer(4);
    Comparable<Integer> o = new Integer(4);
    // Problematic line
    int j = o.compareTo(q);

    if (j == -1)
        System.out.println("yes");
    else
        System.out.println("no");
 }

but this one works:

public static void main(String[] args) throws IOException
 {
    Integer q = new Integer(4);
    Integer o = new Integer(4);

            // Problematic line
    int j = o.compareTo(q);

    if (j == -1)
        System.out.println("yes");
    else
        System.out.println("no");
 }

  }


In other words when is the interface implementation interchangeable as opposed to the creation of a normal class instance? The error comes when I use the compareTo() method which is part of the Comparable interface and is implemented by all Wrapper classes such as Integers.

So I guess Comparable<Integer> q = new Integer(4); and Integer q = new Integer(4); should not make any difference. Could anyone please explain?

Thank you.


Solution

  • The parameter of the Comparable#compareTo() method is of type T where T is the generic type variable of the Comparable type. In other words, for a variable declared as Comparable<Integer>, the method will only accept an Integer. The argument you are trying to pass is declared as type Comparable<Integer> which is incompatible.