Beny Bosko
Beny Bosko

Reputation: 239

Java - Why Iterator need to be generic?

Iterators of the actual List are implemented as inner classes in the List's class. Therefore we can refer to the List's generic type from the inner class. So why iterators are generic? If we call an iterator from the actual List, the next() method will use the Generic type of the List the iterator was called from.

Upvotes: 0

Views: 561

Answers (3)

Seelenvirtuose
Seelenvirtuose

Reputation: 20618

The iterator interface is designed as

public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove();
}

Note the next method. What return type would it have, if the interface weren't generic? It would be

Object next();

So without parameterization you would end up with code like this:

List<String> list = createSomeList();
String s = (String) list.iterator().next();

Note the necessary cast. The whole point of generics is to produce code without the need to cast; this is called type safety. With the current iterator interface you can do

List<String> list = createSomeList();
String s = list.iterator().next();

Upvotes: 0

ernest_k
ernest_k

Reputation: 45319

It isn't given that ALL iterators are implemented as inner classes. Even if it were so, the instance of returned iterator would still be obtained from the type of the collection type (List, in your case)

The key point however is linked to the contract between List and its callers. List/Collection.iterator() should return the a generic iterator based on its type parameter [whether you used an intermediate variable to store the iterator or not].

Upvotes: 0

Derlin
Derlin

Reputation: 9881

Because we override a method from the superclass. If the superclass didn't provide a generic signature, you couldn't override it with a custom object.

Upvotes: 2

Related Questions