Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
不兼容列表<&燃气轮机;在java中使用泛型_Java_Oop_Generics - Fatal编程技术网

不兼容列表<&燃气轮机;在java中使用泛型

不兼容列表<&燃气轮机;在java中使用泛型,java,oop,generics,Java,Oop,Generics,我有以下JAVA代码: List <? extends Number > l3=new List<Number>() ; // List not allowed ? why . and why arrayList is allowed here Integer i=new Integer(5); l3.add(i); // why we can not add i to l3 . 列表变量x; variablex.add(新整数(5));//错误?那为什么呢? 我

我有以下JAVA代码:

List <? extends Number > l3=new List<Number>() ; // List not allowed ? why . and why arrayList is allowed here

Integer i=new Integer(5);

l3.add(i); // why we can not add i to l3 .
列表变量x;
variablex.add(新整数(5));//错误?那为什么呢?

我想知道为什么在编译时会出现这些错误?

在接口中列出这些错误,而您不能实例化接口


ArrayList
List
接口的实现,您只能创建类的对象。

您必须有
List
的具体实现,例如
ArrayList
LinkedList

List <? extends Number> l3 = new ArrayList<Number>() ;

那么为什么不允许在第二种情况下使用它呢?在第二种情况下,您还没有初始化它。您刚刚声明了它。“?扩展数字”如果它不安全,那么为什么允许它?@Michaagus添加到它是不允许的。表达式本身是完全安全的。@通常,在泛型类上调用带有泛型参数(如
add
)的方法时,如果变量的实际类型是通配符,则会产生类型不安全的代码。
还有其他用途?扩展了一些类
,比如当你不需要调用像
add
这样的方法时。现在List@Michaagus你可以调用
add(一个整数)
,一个
List
和一个
List
。让我们从一个基本问题开始:为什么要使用
列表这个问题看起来像是,和。
List <? extends Number> l3 = new ArrayList<Number>() ;
List<?> l3 = new ArrayList<Number>();
// Later...
l3 = new LinkedList<MySpecialTypeYouDidntKnowAbout>();
// And then this doesn't work.
l3.add(new Integer(5));