不兼容列表<&燃气轮机;在java中使用泛型
我有以下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));//错误?那为什么呢? 我
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));