简体   繁体   中英

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

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 , but Manager doesn't implement Comparable<Manager> . Suppose T is Employee , but List<Manager> can't be passed to a parameter of type List<Employee> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM