Java泛型奇怪的行为

Java泛型奇怪的行为,java,generics,Java,Generics,在Java中扩展 接下来的代码是编译: List<Number> list1 = null; List<? super Integer> list2 = null; list2 = list1; List<? super Number> list1 = null; List<? extends Integer> list2= null; list1 = list2; 列表列表1=null; List(1)在第一个示例中,List被ofList捕

在Java中扩展

接下来的代码是编译:

List<Number> list1 = null;
List<? super Integer> list2 = null;
list2 = list1;
List<? super Number> list1 = null;
List<? extends Integer> list2= null;
list1 = list2;
列表列表1=null;

List(1)在第一个示例中,
List
被of
List捕获。(1)在第一个示例中,
List
被of
List捕获。让我们看看如果它编译:

// Suppose list1, and list2 are initialized like this
List<? super Number> list1 = new ArrayList<Object>();  // valid assignment
List<? extends Integer> list2 = new ArrayList<Integer>();  // valid

// had this been valid, list1 and list2 both point to ArrayList<Integer>
list1 = list2;   

// This is fine, as list1 declared type is `List<? super Number>`
list1.add(new Float(2.4f));

// The below code will compile fine, as list2.get(0) type is Integer.
// But it would throw ClassCastException at runtime.
Integer in = list2.get(0);  
//假设list1和list2是这样初始化的

列出让我们看看如果它编译的话会出现什么问题:

// Suppose list1, and list2 are initialized like this
List<? super Number> list1 = new ArrayList<Object>();  // valid assignment
List<? extends Integer> list2 = new ArrayList<Integer>();  // valid

// had this been valid, list1 and list2 both point to ArrayList<Integer>
list1 = list2;   

// This is fine, as list1 declared type is `List<? super Number>`
list1.add(new Float(2.4f));

// The below code will compile fine, as list2.get(0) type is Integer.
// But it would throw ClassCastException at runtime.
Integer in = list2.get(0);  
//假设list1和list2是这样初始化的

ListI没有试图向list2添加数字,但是@Babibu,如果要将
list1
设置为
list2
,则
list1
的类型必须支持
list2
的所有操作。没有人添加任何内容,存在试图分配的情况。@KevinBowersox,正确。我正在使用
List.add
作为分配无效的示例。在第二个示例中,您可以使用
list1
执行的所有操作都必须能够通过
list2
完成。我不是要向list2添加数字,而是@Babibu,如果您要将
list1
设置为
list2
,则
list1
的类型必须支持
list2
的所有操作。没有人添加任何内容,有一个试图分配的任务。@KevinBowersox,正确。我正在使用
List.add
作为分配无效的示例。在第二个示例中,您可以使用
list1
执行的所有操作都必须能够通过
list2
完成。您是否注意到您的赋值在两个代码中都是反向的。将第一个代码更改为-
list1=list2
,它也不会编译。您是否注意到您的赋值在两个代码中都是反向的。将第一个代码更改为-
list1=list2
,它也不会编译。@波希米亚刚刚看到他的第一个代码有不同方向的赋值。因此,这将被编译。将其更改为
list1=list2
将失败。@波希米亚人刚刚看到他的第一个代码具有不同方向的赋值。因此,这将被编译。将其更改为
list1=list2将失败。
List<Number> list1 = null;
List<? super Integer> list2 = null;
list1 = list2;