Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inference variable T has incompatible bounds

Tags:

java

generics

Given a method with the following signature.

public static <T extends Comparable<T>> int dummyMethod(List<T> list, T elem) {
  // Body
}

Of the following two methods only the first compiles successfully.

public void call() {
  MyClass v = new MyClass();
  List<MyClass> ls = new ArrayList<>();
  dummyMethod(ls, v);
}

public void brokenCall() {
  Comparable<MyClass> v = new MyClass();
  List<Comparable<MyClass>> ls = new ArrayList<>();
  dummyMethod(ls, v);    // Compilation error here.
}

The error returned by javac (JDK 8u60) reads as follows:

.\MyClass.java:23: error: method dummyMethod in class MyClass cannot be applied to given types;
    dummyMethod(ls, v);    // Compilation error here.
    ^
  required: List<T>,T
  found: List<Comparable<MyClass>>,Comparable<MyClass>
  reason: inference variable T has incompatible bounds
    equality constraints: MyClass,Comparable<MyClass>
    lower bounds: Comparable<MyClass>
  where T is a type-variable:
    T extends Comparable<T> declared in method <T>dummyMethod(List<T>,T)
1 error

I'm confused as to why the types of the variables provided as arguments to dummyMethod in brokenCall don't match it's signature.

like image 669
Duncan3142 Avatar asked Apr 14 '26 03:04

Duncan3142


1 Answers

In brokenCall, you're making T = Comparable<MyClass>, but Comparable<MyClass> extends Comparable<Comparable<MyClass>> is invalid.

like image 67
Andreas Avatar answered Apr 16 '26 18:04

Andreas