我正在学习Java中的泛型,我接近了一段非常有趣的代码.我知道在Java中将一种类型的列表添加到另一种类型是违法的.
List<Integer> integerList = new ArrayList<Integer>();
List<String> stringList=integerList;
Run Code Online (Sandbox Code Playgroud)
所以在第二行我得到一个编译时错误.
但是如果我在这样的类中创建一个泛型方法,
class GenericClass <E>{
void genericFunction(List<String> stringList) {
stringList.add("foo");
}
// some other code
}
Run Code Online (Sandbox Code Playgroud)
并且在主类中调用带有Integer列表的方法我没有收到任何错误.
public class Main {
public static void main(String args[]) {
GenericClass genericClass=new GenericClass();
List<Integer> integerList= new ArrayList<Integer>();
integerList.add(100);
genericClass.genericFunction(integerList);
System.out.println(integerList.get(0));
System.out.println(integerList.get(1));
}
}
Run Code Online (Sandbox Code Playgroud)
输出
100
foo
为什么我没有收到任何错误?