[英]Why does the inner class complain about generic type?
我有一个实现Iterable的类,以便用户可以使用迭代器。 我正在使用泛型来允许用户使用任何类型并使用该类。
这是下面的工作代码,没有任何警告 -
public class CustomStackUsingArray<Type> implements CustomList<Type>, Iterable<Type> {
Type []arr;
public Iterator<Type> iterator() {
return (new ListIterator());
}
private class ListIterator implements Iterator<Type>{
//Implement Iterator here
}
//Implement other methods here
}
但是,如果我将ListIterator定义为这样 -
private class ListIterator<Type> implements Iterator<Type>
我在Eclipse中收到警告, The parameter Type is hiding the type Type
为什么我在课后指定泛型类型时会抱怨? 为了让我能够在课堂上使用Type,我不应该这样做吗? 我在定义CustomStackUsingArray
时添加了Type
,并且工作正常。
当你说class Something<T>
(可能有多个类型参数)时,你告诉编译器你正在定义一个新的泛型类,以T
为参数。 您可以说private class ListIterator<Type2> implements Iterator<Type2>
; 这本来是合法的,但不是你想要的。 它会创建一个新的泛型类,其中Type2
引用新类型参数的名称。 当你说private class ListIterator<Type> implements Iterator<Type>
,你实际上做的完全相同,但是使用名为Type
而不是Type2
的类型参数。 此Type
与外部类的Type
无关。 此外,在这个新类中,每当你说Type
,你指的是new type参数,这意味着你不能再引用外部类型参数 - 它是隐藏的,这就是Eclipse告诉你的。
这一切都发生是因为您告诉编译器您想要创建一个新的泛型类。 但你真的没有。 你只想要一个内部类,它是你定义的外部泛型类的一部分(我认为)。 因此,您需要取消第一个<Type>
。 它应该按照你想要的方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.