简体   繁体   English

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

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

I wanted to create an Iterator for a generic class which worked fine. 我想为一个通用的类创建一个Iterator,它工作正常。 I thought the iterator would try to iterate using the TypeParameter of the generic class, but apparently that's not the case because Eclipse tells me that an Object is expected. 我以为迭代器会尝试使用泛型类的TypeParameter进行迭代,但是显然并非如此,因为Eclipse告诉我期望有一个Object。

If someone knows what I've done wrong, I would be very happy. 如果有人知道我做错了什么,我会很高兴。

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

You need to specify the generic parameters of your base interfaces. 您需要指定基本接口的通用参数。
Otherwise, you'll be implementing Iterable non-generically, and the type parameter will become Object . 否则,您将非通用地实现Iterable ,并且type参数将变为Object

If you want to make your class generic like GenericClass<T extends OtherClass> then you should be implementing Comparable<T> and Iterable<T> , the T in both cases is the same T declared by GenericClass . 如果你想使你的类通用像GenericClass<T extends OtherClass>那么你应该实现Comparable<T>Iterable<T>T在两种情况下是一样T的宣布GenericClass

That way when you do a generic type instantiation as follows - 这样,当您执行通用类型实例化时,如下所示:

 GenericClass<InstanceOfOtherClass> //...

The effect would be that it is implementing Comparable<InstanceOfOtherClass> and Iterable<InstanceOfOtherClass> , which makes the method signatures match. 结果将是它正在实现Comparable<InstanceOfOtherClass>Iterable<InstanceOfOtherClass> ,这使方法签名匹配。

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

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