扩展和超级的通用概念 [英] Generic concept of extends and super
问题描述
通用扩展背后的概念是什么,为什么不允许修改 列表;为什么在我将一个字符串添加到list时,它会引发编译时错误,因为String扩展了Object并且应该是合法的.
What is the concept behind the Generic extend that why is it not allowed to modify the list; why does it throw a compile time error when I add a string to list , since String extends Object and should be legal.
如果这会导致编译错误,那么创建的列表的用途是什么.
If this gives compilation error , then what is the use of that list that is created then.
List<? extends Object> ls=new ArrayList<String>();
ls.add("asd"); // compilation error
并且在超级的情况下进行编译.
And it compiles in the case of super.
List<? super Integer> ls1=new ArrayList<Object>();
ls1.add(1);
我已经阅读了Kathy Sierra和Javadoc,但无法理解这意味着什么.请通过示例详细说明我.
I have read Kathy Sierra and Javadoc, but am not able to understand what this means. Please give me a detailed explanation with examples to understand this.
推荐答案
您不能将字符串添加到List<? extends Object>
,因为?可以是任何东西.
You can't add Strings to a List<? extends Object>
because ? could be anything.
如果要将放入列表,则其类型参数应该是要放入的类型的超类.(包括类型本身.)
If you want to put things into a list, its type parameter should be a superclass of the type you want to put in. (This includes the type itself.)
如果要从列表中获取 ,则其type参数应该是要取出的类型的子类. (这包括类型本身.)
If you want to get things from a list, its type parameter should be a subclass of the type you want to take out. (This includes the type itself.)
这可以用PECS的缩写来记住-生产者扩展,消费者超级.
This can be remembered with the acronym PECS - producer-extends, consumer-super.
这篇关于扩展和超级的通用概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!