List<子类>传入someMethod(List<父类> alist)问题

List<子类>是不能传进someMethod(List<父类> alist)的,List<子类>并不是List<父类>的子类,可以利用范型改造方法来解决此问题。

详细示例:

1
2
3
public interface IParam {
String getAName();
}
1
2
public class SuperClass {
}
1
2
3
4
5
6
public class SubClass extends SuperClass implements IParam{
@Override
public String getAName() {
return "a name of sub class";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class TestParam {    
public void tryInheritance(SuperClass superClass){
System.out.println("tryInheritance");
}
public void tryInterface(IParam iParam) {
System.out.println("tryInterface");
}

public void tryInheritanceList(List<SuperClass> superClassList){
System.out.println("tryInheritance list");
}
public void tryInterfaceList(List<IParam> iParam) {
System.out.println("tryInterface list");
}

public <T extends IParam> void tryGeneric(List<T> listT){
System.out.println("tryGeneric");
}


public static void main(String[] args){
TestParam t = new TestParam();
SuperClass superC = new SuperClass();
SubClass subC = new SubClass();
List<SuperClass> superList = new ArrayList<SuperClass>();
List<SubClass> subList = new ArrayList<SubClass>();

t.tryInheritance(subC); // 参数类型SuperClass,传入子类ok
t.tryInterface(subC); // 参数类型IParam,传入实现类ok

// List<子类>并不是List<父类>的子类
// t.tryInheritanceList(subList); // 参数类型List<SuperClass>,传入List<子类>,编译错误
// t.tryInterfaceList(subList); // 参数类型List<IParam>,传入List<实现类>,编译错误

// 利用范型来解决问题
t.tryGeneric(subList); // 参数类型List<T extends IParam>,传入List<实现类>, ok
}
}