具有泛型类型参数的Java类,该参数实例化不同的泛型接口
我发现了一个关于java不能用不同类型参数实现同一接口两次的限制的例子。(例如,您不能是具有泛型类型参数的Java类,该参数实例化不同的泛型接口,java,generics,Java,Generics,我发现了一个关于java不能用不同类型参数实现同一接口两次的限制的例子。(例如,您不能是Iterable和Iterable),但我没有发现以下情况的任何讨论 我可以说 public class A implements Iterable<Integer> { public Iterator<Integer> iterator() { throw new UnsupportedOperationException();
Iterable
和Iterable
),但我没有发现以下情况的任何讨论
我可以说
public class A implements Iterable<Integer> {
public Iterator<Integer> iterator() {
throw new UnsupportedOperationException();
}
}
表示String
正在隐藏String
,而不是隐藏Integer
。我甚至不知道那是什么意思A
允许使用Iterable
,而A
不允许-这是我问题的关键
编辑: 我发现我的例子有问题。例如,我从自己的界面
LinkableVertex
更改为Iterable
,认为这没有什么区别OurLinkClass
已实现LinkableEdge
。Eclipse中的实际错误是:
Bound mismatch: The type OurLinkClass is not a valid substitute for the
bounded parameter <E extends LinkableEdge<? extends LinkableVertex<E>>> of
the type LinkableVertex<E>
绑定不匹配:类型OurLinkClass不是
有界参数隐藏意味着泛型使用的名称可能隐藏了一个类:java.lang.String
在类定义中使用泛型和在变量(局部、参数、字段等)定义中使用泛型有很大的区别
定义这一点是不一样的:
public class A<String> {
//^----^----- name of your generic used in the class
public String getFoo() {
}
}
公共A类{
//^----^-----类中使用的泛型的名称
公共字符串getFoo(){
}
}
而不是宣布:
A<String> a; //here A will work with generics but using java.lang.String class
A//在这里,A将使用泛型,但使用java.lang.String类
此外,您的类可以实现使用泛型的接口,但这并不意味着您的类也必须使用泛型。下面是一个例子:
class MyClass<T> implements Iterable<T> {
//this means MyClass will use a generic of name T and implements Iterable
//to support the same generic T used in the class
}
class AnotherClass implements Iterable<String> {
//this means that AnotherClass doesn't support generics
//and implements Iterable for java.lang.String only.
}
类MyClass实现了Iterable{
//这意味着MyClass将使用T的泛型名称并实现Iterable
//支持类中使用的相同泛型T
}
类另一个类实现Iterable{
//这意味着另一个类不支持泛型
//并仅为java.lang.String实现Iterable。
}
public class A实现了Iterable—它对我来说工作得很好您的类型看起来应该工作得很好。出了什么问题?它起作用了:等一下,我同意,这对我现在起作用了。我将尝试找出以前在IDE中查看它时出现的错误。添加了一个编辑以清除代码示例中出现的错误。啊,那么,在这种情况下,字符串作为泛型类型名,可以引用另一种类型,如Integer?谈论混淆!哇,是的,它只是允许字符串作为变量类型名。除了躲起来,这完全没关系<代码>公共类A实现了Iterable{
,这是正确的。请注意泛型的名称:)@JoshuaGoldberg我不知道他们为什么允许这样做。这是一个常见的混淆原因。IMHO类型参数最多应限制为3个字符。
Bound mismatch: The type OurLinkClass is not a valid substitute for the
bounded parameter <E extends LinkableEdge<? extends LinkableVertex<E>>> of
the type LinkableVertex<E>
public class A<String> {
//^----^----- name of your generic used in the class
public String getFoo() {
}
}
A<String> a; //here A will work with generics but using java.lang.String class
class MyClass<T> implements Iterable<T> {
//this means MyClass will use a generic of name T and implements Iterable
//to support the same generic T used in the class
}
class AnotherClass implements Iterable<String> {
//this means that AnotherClass doesn't support generics
//and implements Iterable for java.lang.String only.
}