0

Why does test1 cause an error while test2 does not? According to test2, <T extends Comparable<T>>. But Manager implements Comparable<Employee>, not Comparable<Manager>, so why doesn't test2 cause an error?

public class Employee implements Comparable<Employee>{...}
 
public class Manager extends Employee{...}
 
public static <T extends Comparable<T>> void test1(List<T> t){ }
 
public static <T extends Comparable<T>> void test2(T t){ }
 
--------------------
 
List<Manager> listManager = new ArrayList<>();
 
test1(listManager);        //ERROR
 
test2(new Manager());      

enter image description here

Error message:

Required type:List<T>
Provided:List<Manager>
reason: Incompatible equality constraint: Employee and Manager

Any suggestion would be appreciated. Thank you.

mingww li
  • 3
  • 2
  • 2
    Please replace the image with text. We discourage images when text will do. Personally, I can't access that image from my work network and so can't help answer your question. A lot of other readers are in the same situation. – Software Engineer Dec 20 '20 at 07:34

1 Answers1

4

Remember that T can be any reference type. You are assuming that the compiler chooses T to be Manager, but if it does so, your code will, as you said, fail to compile. The compiler's job is to compile your code, so it will try to find a T such that your code does compile.

If T is Employee, the code would compile. Employee implements Comparable<Employee>. You can also pass a Manager to a parameter of type Employee, since Manager inherits from Employee, so all is good.

In test1 however, no T will make your code compile. Suppose T is Manager, butManager doesn't implement Comparable<Manager>. Suppose T is Employee, but List<Manager> can't be passed to a parameter of type List<Employee>.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 3
    Just to note, `test1` can be made to compile by changing the bound to `Comparable super T>`. – Slaw Dec 20 '20 at 07:19