简体   繁体   English

ArrayList用不同的数据类型初始化

[英]ArrayList initialise with different data type

Firstly, why does the first line compile while the second does not? 首先,为什么第一行编译而第二行不编译? Secondly, in the case of the second line, do both types always need to be the same ie Integer on the left and Integer on the right. 其次,在第二行的情况下,两种类型是否总是需要相同,即左侧是Integer,右侧是Integer。 Or is it possible to have different types on the left and the right? 还是有可能在左侧和右侧具有不同的类型?

    List<? super Integer> nums1 = new ArrayList<Number>();  //COMPILES
    List<Integer> nums2 = new ArrayList<Number>();          //DOES NOT COMPILE

Your question is esentially a duplicate of this SO-article but in short: 您的问题本质上是该SO文章的重复,但总而言之:

? super T ? super T means "anything that is a superclass of T". ? super T意思是“任何属于T的超类的东西”。 Number is a superclass of Integer so this is accepted. NumberInteger的超类,因此可以接受。 The second line doesn't work simply because Number is not Integer . 第二行不能仅仅因为Number不是Integer而起作用。 It wouldn't work vice versa, either so 反之亦然,这是行不通的

ArrayList<Number> nums2 = new ArrayList<Integer>();

leads to a compile error as well. 也会导致编译错误。 For that you can use 为此,您可以使用

ArrayList<? extends Number> nums2 = new ArrayList<Integer>(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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