Java通用方法:超级无法使用? [英] Java generic methods: super can't be used?

查看:104
本文介绍了Java通用方法:超级无法使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这样的方法:

pre $ protected void collectSelectedItems(ListSelectionModel lsm,
Collection< ;? super MyItemClass>结果){
for(int i:GUI.getSelectionIndices(lsm))
{
result.add(getItemByDisplayIndex(i));
}
}

我想返回集合而不是一个void方法:

 保护< T super MyItemClass>收集和LT; T> 
collectSelectedItems(ListSelectionModel lsm,Collection< T> result){
for(int i:GUI.getSelectionIndices(lsm))
{
result.add(getItemByDisplayIndex(i)) ;
}
返回结果;
}

的目的是做这样的事情(其中 MyItemClass扩展MyItemBaseClass ):

  List< MyItemBaseClass> list = 
collectSelectedItems(lsm,new ArrayList< MyItemBaseClass>());

但是在 super 上出现语法错误>:
$ b


令牌超级的语法错误,预期

什么给了?我可以解决这个问题吗?

解决方案

以下链接解释了为什么不允许这样做:



http://www.angelikalanger.com/GenericsFAQ/FAQSections /TypeParameters.html#FAQ107



它基本上只是说在类型参数中使用超级不会买任何东西,因为如果允许这样做,删除可能会将其清除为 Object ,这没有多大意义。


So I have this method:

protected void collectSelectedItems(ListSelectionModel lsm, 
         Collection<? super MyItemClass> result) {
    for (int i : GUI.getSelectionIndices(lsm))
    {
        result.add(getItemByDisplayIndex(i));
    }
}

I'd like to return the collection instead of having a void method:

protected <T super MyItemClass> Collection<T> 
  collectSelectedItems(ListSelectionModel lsm, Collection<T> result) {
    for (int i : GUI.getSelectionIndices(lsm))
    {
        result.add(getItemByDisplayIndex(i));
    }
    return result;
}

with the intent of doing something like this (where MyItemClass extends MyItemBaseClass):

List<MyItemBaseClass> list = 
   collectSelectedItems(lsm, new ArrayList<MyItemBaseClass>());

but I get a syntax error on the super:

Syntax error on token "super", , expected

What gives? Can I fix this?

解决方案

Here's one link that explains why this is not allowed:

http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ107

It basically just says that use super in type parameters "does not buy you anything", since if this is allowed, erasure will probably just erase it to Object, which does not make much sense.

这篇关于Java通用方法:超级无法使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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