This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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?
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.
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.