本文介绍了说 < 有什么用?

问题描述

所以我在查看一些 Java 代码时偶然发现:

So I was looking over some Java code and stumbled upon:

List<? extends SomeObject> l;

基本上这个列表接受所有属于某种 SomeObject 的对象 - SomeObject 本身或其继承者.但是根据多态性,它的继承者也可以被视为 SomeObject,所以这也可以:

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;

在这里你不能说Listl = new ArrayList;(不允许)

List<? extends SomeObject> l;

你可以说

列表(允许)

但请注意,在 List不能添加任何东西到你的列表 l 因为?代表未知类(当然,除了 null).

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).

更新:对于您在评论中的问题如果我无法向列表添加任何内容,我可以用它做什么?

现在考虑这样一种情况,您必须编写一个函数来打印您的列表,但请注意,它必须只接受一个 List,其中的对象是您的 SomeObject 的子类.在这种情况下,如上所述,您不能使用

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 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
        }

这篇关于说 &lt; 有什么用?

09-09 17:24