Java 泛型 - 类型参数 String 隐藏了类型 String
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10178377/
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 generics - The type parameter String is hiding the type String
提问by Shengjie
In my interface:
在我的界面中:
public <T> Result query(T query)
In my 1st subclass:
在我的第一个子类中:
public <HashMap> Result query(HashMap queryMap)
In my 2nd subclass:
在我的第二个子类中:
public <String> Result query(String queryStr)
1st subclass has no compilation warning at all while 2nd subclass has: The type parameter String is hiding the type String? I understand my parameter is hidden by the generics type. But I want to understand underneath what exactly happened?
第一个子类根本没有编译警告,而第二个子类有:类型参数 String 正在隐藏类型 String?我知道我的参数被泛型类型隐藏了。但我想了解到底发生了什么?
回答by Louis Wasserman
It thinks you're trying to create a type parameter -- a variable-- whose name is String
. I suspect your first subclass simply doesn't import java.util.HashMap
.
它认为您正在尝试创建一个类型参数——一个变量——其名称是String
. 我怀疑你的第一个子类根本没有 import java.util.HashMap
。
In any event, if T
is a type parameter of your interface-- which it probably should be -- then you shouldn't be including the <String>
in the subclasses at all. It should just be
无论如何,如果T
是您的接口的类型参数——它可能应该是——那么您根本不应该<String>
在子类中包含 。它应该只是
public interface Interface<T> {
public Result query(T query);
}
public class Subclass implements Interface<String> {
...
public Result query(String queryStr) {
...
}
}