File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Iterating over generic List Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Iterating over generic List" Watch "Iterating over generic List" New topic

Iterating over generic List

Sam Samson
Ranch Hand

Joined: Oct 08, 2011
Posts: 63


Could someone please explain to me why iterating over a List that uses wildcard and super isn't possible? If I'm passing a List<Object> that list can contain everything, a Zoo, a Person, a String etc. But T should be Object anyway in the for-loop. So what's the problem?

Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

If you look closely at the error message, you'll find it's telling you exactly what's wrong.

This: doFoo(List<? super T> list)

says that the List can contain any supertype of T. So if T is, for example, Integer, then List's elements could be Numbers or Comparables or Objects or...

but this: for(T t : list)

says that you expect everything in List to be a T.

So, if T is Integer, then the doFoo() signature allows List<Number>, which might include some Doubles, or even List<Object>, which might include some JPanels or java.sql.ResultSets. Therefore, the compiler can't guarantee that when you iterate, that you'll actually get a T (an Integer) for each element.
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

You're passing in a List of some type that is higher in the hierarchy than T. So it could be a List<Object>, for instance, which could contain anything, as you say. But then you're effectively casting everything to a T. T can be anything. What if, for example, T is String, and you pass in a List<Object> containing Objects? That cast is never going to work. Why do you say that T should be Object in the loop? If T can only be Object, then the method should never have been generic.
Sam Samson
Ranch Hand

Joined: Oct 08, 2011
Posts: 63

*argh*, didn't see that, thanks!
I agree. Here's the link:
subject: Iterating over generic List
It's not a secret anymore!