名单&LT ;?扩展MyType> [英] List<? extends MyType>

查看:88
本文介绍了名单&LT ;?扩展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:


在List< capture#3类型中添加方法add(捕获#3 - 扩展
MyType)
?扩展MyType>不适用
作为参数(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)

任何想法?

推荐答案

你不能用extend来做put。查看泛型 - 获取和放置规则

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

这篇关于名单&LT ;?扩展MyType&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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