java Java泛型列表参数不可能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4163826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java generic List parameter not possible?
提问by Jonathan
i have a simple method that takes a generic List parameter but for some reason my IDE(Eclipse) states how it cannot be resolved?
我有一个简单的方法,它采用一个通用的 List 参数,但由于某种原因,我的 IDE(Eclipse) 说明它是如何无法解决的?
Am i doing something wrong here
我在这里做错了吗
private OnClickListener removeFieldListener(final LinearLayout layout,
List<T> viewList) {
return new OnClickListener() {
@Override
public void onClick(View v) {
int indexToDelete = layout.indexOfChild(v);
}
};
}
回答by Riduidel
In that case, the T parameter has to be defined somewhere. As I guess your class does not declares this parameter, you have to put it in your method declaration, like
在这种情况下,必须在某处定义 T 参数。我猜你的类没有声明这个参数,你必须把它放在你的方法声明中,比如
private <T> OnClickListener removeFieldListener(final LinearLayout layout,
List<T> viewList) {
But this will only move the problem to the caller of this method ...
但这只会将问题转移到此方法的调用者身上......
回答by Andrzej Doyle
Riduidel is right in that the problem is that you haven't declared the T
anywhere.
Riduidel 是对的,问题在于你没有声明T
任何地方。
Depending on what you want to do with the contents of the list, chances are you can just use a wildcard. List<?> viewList
would work if you're only pulling Object
s out of it; or List<? extends IListener>
will allow you to get IListeners out of it, etc.
根据您想对列表内容做什么,您可能只使用通配符。 List<?> viewList
如果你只是把Object
s拉出来,它会起作用;或List<? extends IListener>
将允许您从中获取 IListeners 等。
In general, you don't need a generic parameter if it only appears once within your method, and you should use a wildcard instead. If it doesappear multiple times, for example you remove things from the list and assign them to variables of type T
, then you do indeed need the wildcard and you should parameterise your method as Riduidel suggests.
通常,如果泛型参数在您的方法中只出现一次,则您不需要它,您应该使用通配符。如果它确实出现多次,例如您从列表中删除内容并将它们分配给 type 的变量T
,那么您确实需要通配符并且您应该按照 Riduidel 的建议参数化您的方法。