演员表列出<我的界面>我的界面>
我正在用java编写一段代码,并且想封装我的对象并且只返回接口。
简而言之,这是我的问题,我有一个包含列表的类,并且我有一个返回列表的 getter。如何返回接口列表?
如果没有收到此错误警告:
列表是原始类型。对泛型类型 List 的引用应该参数化
为了让您清楚地了解这段代码是我的问题的一个示例:
public class Employee{
private List<MyObject> myObjects;
public List<MyInterface> getMyObjects(){
return myObjects;
}
}
其中 MyObject 实现 MyInterface 并返回 myObjects 给出了问题。
提前致谢。
I'm writing a piece of code in java and would like to encapsulate my object and only return interfaces.
Now in short this is my problem I have a class containing a list, and I have a getter which returns a List. How can I return a list of the interface ?
Without getting this error warning :
List is a raw type. References to generic type List should be parameterized
To give you a clear picture this piece of code is an example of my problem :
public class Employee{
private List<MyObject> myObjects;
public List<MyInterface> getMyObjects(){
return myObjects;
}
}
where MyObject implements MyInterface and return myObjects gives the problem.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果
MyObject
实现MyInterface
您可以将返回类型更改为List
。请注意,在这种情况下,编译器不允许您在返回的列表上调用
add(...)
,除非您在此处进行强制转换。但是,由于您仅返回接口,我想您不打算向返回的列表添加任何内容,所以应该没问题。If
MyObject
implementsMyInterface
you could change the return type toList<? extends MyInterface>
.Note that in this case the compiler won't allow you to call
add(...)
on the returned list, except you'd cast here. However, since you're returning interfaces only, I guess you're not planning to add anything to the returned list, so you should be fine.只需将接口列表声明为实例变量即可。
Simply declare a list of your interface as your instance variable.
我只是按照您需要的方式定义实例属性:
I'd simply define the instance attribute the way you need it:
尽管
MyObject
实现了MyInterface
,但List
扩展List却不为真。 ;
- 请参阅这篇优秀文档了解更多信息。为了告知编译器您的意图,请指定方法签名,如下所示:Even though
MyObject
implementsMyInterface
, it is not true thatList<MyObject>
extendsList<MyInterface>
- see this excellent document for more info. In order to inform the compiler of your intentions, specify the method signature like so:使用
checkedCollection(集合 c,类类型)
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Collections.html#checkedCollection(java.util.Collection, java.lang.班级)
Use
checkedCollection(Collection c, Class type)
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Collections.html#checkedCollection(java.util.Collection, java.lang.Class)
您无法将
List
转换为List
。因此,尝试将myObjects
定义为List
或使用以下内容:You cannot cast
List<MyObject>
toList<MyInterface>
. So try to definemyObjects
asList<MyInterface>
or use the following: