Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Iterating over generic List

 
Sam Samson
Ranch Hand
Posts: 63
IntelliJ IDE Java jQuery
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

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
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 63
IntelliJ IDE Java jQuery
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
*argh*, didn't see that, thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic