Question

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.

Was it helpful?

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.

OTHER TIPS

A Comparable<Integer> can only compare Integer(s).

// This will work
Comparable<Integer> o = new Integer(4);
int j = o.compareTo(new Integer(4));
// of course j will be 0, because 4 is equal to 4.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top