0

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());
    }

}

}
1
  • 1
    Read the compiler warnings Commented Jun 7, 2013 at 16:28

2 Answers 2

8
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.

Sign up to request clarification or add additional context in comments.

1 Comment

"Otherwise, you'll be implementing Iterable<Object>." No they won't. They'll be implementing Iterable (and Comparable). Iterable is not the same thing as Iterable<Object>
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.