2

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.

2
  • What is your question? Commented Jan 4, 2014 at 1:30
  • Yes. A Comparable<Integer> is something you can compare to an Integer - not something that you can compare to another Comparable<Integer>. Commented Jan 4, 2014 at 1:30

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.