凝聚"超级"

Dan*_* R. 7 java generics

我想写一个像这样的Interator:

class Plant { }
class Tree extends Plant { }
class Maple extends Tree { }

// Iterator class: compiler error on the word "super".
class MyIterator<T super Maple> implements Iterator<T> {
    private int index = 0;
    private List<Maple> list = // Get the list from an external source.

    public T next() {
         Maple maple = list.get(index++);
         // Do some processing.
         return maple;
    }

    // The other methods of Iterator are easy to implement.
}
Run Code Online (Sandbox Code Playgroud)

从概念上讲,这个想法是让迭代器看起来像返回树或植物(即使它们总是Maples),而不为每个迭代器编写单独的类.

但是当我通过时,编译器不喜欢它T super Maple; 显然你只能用一个类来生成T extends Something.有谁知道一个很好的方法来完成同样的事情?

我要求的动机是我有一个程序,它的API使用接口.我想有一个方法返回接口的迭代器(对于API),另一个方法返回实现类的迭代器(供内部使用).

Edw*_*rzo 3

如果Maple是 aTree和 a Plant,因为它扩展了两者,那么您要使用 super 子句的意义何在?您可以通过经典子类型多态性分配给MappleObjecttoTree或 toPlant references.

? extends T都是? super T通配符,声明为类型参数以替换类型参数T.

您打算做的是定义类型参数的界限,而不是类型参数的界限。您可以简单地将类型参数声明为 T,没有界限,然后在使用它时,使用通配符作为类型参数。

class MyIterator<T> implements Iterator<T> { ... }
Run Code Online (Sandbox Code Playgroud)

当你使用它时:

MyIterator<? super Maple> iter;
Run Code Online (Sandbox Code Playgroud)