问题描述
List< ;?扩展SomeObject>升;
基本上这个列表接受SomeObject的所有对象 - SomeObject本身或它的继承者。但是根据polyphophism,继承者也可以像SomeObject那样成为seens,所以这也可以工作:
List< SomeObject>升;
那么为什么有人会使用第一个选项,而第二个选项是明确定义的并且几乎相同?
List< SomeObject>升;
在这里你不能说 List< SomeObject> l = new ArrayList< SubClassOfSomeObjectClass> ;;
(不允许)
适用于
列表与LT ;?扩展SomeObject>升;
您可以说
列表< ;?扩展SomeObject> l = new ArrayList< SubClassOfSomeObject> ;;
( allowed )
但是请注意,在名单< ;?扩展SomeObject> l = new ArrayList< SubClassOfSomeObject> ;;
您无法向您的列表添加任何内容l ,因为?代表未知课程(课程无效)。
更新: c $ c>如果我不能添加任何东西,我可以做什么?
现在考虑一个你有编写一个函数来打印列表,但请注意,它只能接受一个带有SomeObject的子类的对象的列表。在这种情况下,如上所述,您不能使用
public void printList(List someList)
那么你会怎么做?你会做类似于
public void printList(List< ;? extends SomeObject> someList){
for(SomeObject myObj :someList){
//在myObj
上处理读取操作}
So I was looking over some Java code and stumbled upon:
List<? extends SomeObject> l;
basically this list accepts all objects that are some kind of SomeObject - SomeObject itself or its inheritors. But according to polymophism, it's inheritors can also be seens as SomeObject, so this would work as well:
List<SomeObject> l;
So why would someone use the first option when the second is clearly defined and virtually identical?
List<SomeObject> l;
In this you cannot say List<SomeObject> l = new ArrayList<SubClassOfSomeObjectClass>;
(not allowed)wheres for
List<? extends SomeObject> l;
you can say
List<? extends SomeObject> l = new ArrayList<SubClassOfSomeObject>;
(allowed)
But note that in List<? extends SomeObject> l = new ArrayList<SubClassOfSomeObject>;
you cannot add anything to your list l because ? represents unknown class (Except null of-course).
Update: For your question in the comment What could I possibly do with a list if I cannot add anything to it?
Now consider a case in which you have to write a function to print your list but mind you it must only accept a List having objects which are subclasses of your SomeObject. In this case as I stated above you cannot use
public void printList(List<SubClassOfSomeObjectClass> someList)
So what would you do? You would do something like
public void printList(List<? extends SomeObject> someList) {
for(SomeObject myObj : someList) {
//process read operations on myObj
}
这篇关于用什么说< ;?扩展SomeObject>而不是< SomeObject>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!