首页 / JAVA / Java中忽略了泛型
Java中忽略了泛型
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java中忽略了泛型,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1396字,纯文字阅读大概需要2分钟。
内容图文
所以我有这个Java代码:
public <A extends Action> List<A> getActionsFor(Actor a) {
List<A> theActions = super.getActionsFor(a);
for (Action ac: a.getItemCarried().getActions()) {
theActions.add(ac);
}
return theActions;
}
由于某种原因,javac拒绝.add(ac)声称add(A)不能应用于Action.
我在这里错过了一些关键吗?我可以通过在两个包中创建依赖项来解决这个问题,但我真的不想这样做.
有问题的所有类都已正确导入,并且每个方法都调用了,所以我真的很遗憾为什么它不能接受A扩展的类类型.
任何建议即使你不确定也会受到赞赏,因为我必须在接下来的6个小时内得到修复,否则我将需要创建这种依赖.
解决方法:
Am I missing something key here?
A是扩展Action的东西,ac也是扩展Action的东西.然而,这有点像设施
Yesterday I saw someone.
Someone is the President
Therefor, yesterday I was the President.
问题是编译器无法知道A和Action是Action的兼容子类
一个简单的解决方法是不要那么具体.在此方法中使用Action而不是A.
public List<Action> getActionsFor(Actor a) {
// this has to return a copy of the List or you will be modifying an original
List<Action> theActions = super.getActionsFor(a);
for (Action ac: a.getItemCarried().getActions()) {
theActions.add(ac); // ac is an Action so all good.
}
return theActions;
}
或者你可以做你所拥有的,但更复杂
public <A extends Action> List<A> getActionsFor(Actor<A> a) {
List<A> theActions = super.getActionsFor(a);
for (A ac: a.getItemCarried().getActions()) {
theActions.add(ac); // ac is an A, so all good.
}
return theActions;
}
内容总结
以上是互联网集市为您收集整理的Java中忽略了泛型全部内容,希望文章能够帮你解决Java中忽略了泛型所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。