简体   繁体   中英

Java: Type mismatch with iterator of generic class

I wanted to create an Iterator for a generic class which worked fine. 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.

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 .

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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