mingww li
mingww li

Reputation: 3

<T extends Comparable<T>>

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.

Upvotes: 0

Views: 323

Answers (1)

Sweeper
Sweeper

Reputation: 271050

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>.

Upvotes: 4

Related Questions