繁体   English   中英

Java:类型与通用类的迭代器不匹配

[英]Java: Type mismatch with iterator of generic class

我想为一个通用的类创建一个Iterator,它工作正常。 我以为迭代器会尝试使用泛型类的TypeParameter进行迭代,但是显然并非如此,因为Eclipse告诉我期望有一个Object。

如果有人知道我做错了什么,我会很高兴。

public class GenericClass<T extends OtherClass> implements Comparable, Iterable
{
    private ArrayList<T> list = new ArrayList<T>();
    [...]
    @Override
    public Iterator<T> iterator()
    {
    Iterator<T> iter = list .iterator();
    return iter;
}
    [...]
}



public class Main
{
public static void main(String[] args)
{
    GenericClass<InstanceOfOtherClass> gen = new GenericClass<InstanceOfOtherClass>("Aius");

    for(InstanceOfOtherClass listElement : gen) // This is the problem line; gen is underlined and listElement is expected to be an Object
    {
        System.out.println(listElement.getName());
    }

}

}
implements Comparable, Iterable

您需要指定基本接口的通用参数。
否则,您将非通用地实现Iterable ,并且type参数将变为Object

如果你想使你的类通用像GenericClass<T extends OtherClass>那么你应该实现Comparable<T>Iterable<T>T在两种情况下是一样T的宣布GenericClass

这样,当您执行通用类型实例化时,如下所示:

 GenericClass<InstanceOfOtherClass> //...

结果将是它正在实现Comparable<InstanceOfOtherClass>Iterable<InstanceOfOtherClass> ,这使方法签名匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM