1

I am trying to construct an object using the following constructor in Java:

public UnaryNumberContract(Comparable<Number> expectedValue, Operations operator, Invariant inv) {
  super(inv, operator);
  this.expectedValue = expectedValue;
}

I am passing on the following parameters:

Comparable<Number> zero = new Integer(0); 
UnaryNumberContract contract = new UnaryNumberContract(zero, Operations.NOT_EQUALS, (Invariant) inv);

And I keep getting a Type mismatch: cannot convert from Integer to Comparable<Number>

I've checked and Number is a super class of Integer, so I don't quite understand what is goinh wrong here.

Tiago Veloso
  • 8,513
  • 17
  • 64
  • 85
  • Possible duplicate of http://stackoverflow.com/questions/2112343/java-integer-obj-cant-cast-to-comparable – rid Jun 27 '11 at 18:30
  • Also possible duplicate of http://stackoverflow.com/questions/480632/why-doesnt-java-lang-number-implement-comparable – Matten Jun 27 '11 at 18:31

3 Answers3

3

If you replace references to Comparable<Number> with Comparable<? extends Number>, that will solve the issue.

Also, see this When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

Community
  • 1
  • 1
Darth Ninja
  • 1,049
  • 2
  • 11
  • 34
2

The problem is that Integer does not implement Comparable<Number>, it implements Comparable<Integer>.

Comparable<Integer> does not inherit from Comparable<Number> and this is why it's not possible to cast it.

What you can do is use Number for your parameter type. Integer does inherit Number and you will not have the same problem.

Marcelo
  • 11,218
  • 1
  • 37
  • 51
0

That is because Integer doesn't implement Comparable<Number> it is an implements Comparable<Integer>.

All Implemented Interfaces: Serializable, Comparable<Integer>

Relevant Integer JavaDoc.