【问题标题】:Why does the inner class complain about generic type?为什么内部类抱怨泛型类型?
【发布时间】:2017-07-24 03:02:22
【问题描述】:

我有一个实现 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,效果很好。

【问题讨论】:

  • 这在某处有重复,但是当您重新声明它时,您从顶级泛型中隐藏了 &lt;Type&gt; 参数。
  • 如果你认为你必须说class ListIterator&lt;Type&gt; 才能在你的内部类中使用Type——不,你不需要。

标签: java generics


【解决方案1】:

当您说class Something&lt;T&gt;(可能具有多个类型参数)时,您是在告诉编译器您正在定义一个 泛型类,并以T 作为其参数。你可以说private class ListIterator&lt;Type2&gt; implements Iterator&lt;Type2&gt;;这本来是合法的,但不是你想要的。它会创建一个新的泛型类,其中Type2 指的是新类型参数的名称。当你说private class ListIterator&lt;Type&gt; implements Iterator&lt;Type&gt; 时,你实际上是在做同样的事情,只是类型参数名为Type 而不是Type2。这个Type 与外部类的Type 没有任何联系。另外,在这个新类中,每当你说Type 时,你指的是 new 类型参数,这意味着你不能再引用外部类型参数——它是隐藏的,这就是Eclipse 正在告诉你。

这一切都是因为你告诉编译器你想创建一个新的泛型类。但你真的没有。你只想要一个内部类,它是你定义的外部泛型类的一部分(我认为)。因此,您需要省略第一个&lt;Type&gt;。它应该按照你想要的方式工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多