列表<?扩展 MyType> [英] List&lt;? extends MyType&gt;

查看:25
本文介绍了列表<?扩展 MyType>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于泛型的 Java 问题.我声明了一个通用列表:

I have a Java question about generics. I declared a generic list:

List<? extends MyType> listOfMyType;

然后在某些方法中,我尝试实例化并将项目添加到该列表中:

Then in some method I try instantiate and add items to that list:

listOfMyType = new ArrayList<MyType>();
listOfMyType.add(myTypeInstance); 

其中 myTypeInstance 只是一个 MyType 类型的对象;它不会编译.它说:

Where myTypeInstance is just an object of type MyType; it won't compile. It says:

方法 add(capture#3-of ? extendsMyType) 在类型 List 不适用对于参数(MyType)

The method add(capture#3-of ? extends MyType) in the type List<capture#3-of ? extends MyType> is not applicable for the arguments (MyType)

有什么想法吗?

推荐答案

您不能使用 extends 执行放置".查看泛型 - 获取和放置规则.

You cannot do a "put" with extends . Look at Generics - Get and Put rule.

这篇关于列表<?扩展 MyType>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆