Originally posted by Graeme Byers:
What types must I code in the for-loop to add() all its elements ?
Since the type is ? super Dog, that leaves three possible types:
- Dog
- Animal
- Object
Since you can't know which one it is, the widest one is the only one available when iterating: Object.
Now of course, you can't add Object to your list - what if the actual type is Animal or Dog?
Again the rules, but a bit more expanded:
? super X:[LIST]Add: X or a subclass / implementation. Basically anything that IS-A XIterate: only Object? extends X:Add: nothing. You don't know the actual type, so you don't know what to add.Iterate: X (or any superclass through widening)X:Add: X or a subclass / implementation. Basically anything that IS-A XIterate: X (or any superclass through widening)[/LIST]
Since you need to both add and iterate, you must limit your type to an exact class - no super or extends.
As a side note, that code will most likely throw a ConcurrentModificationException. You are in fact modifying the list while iterating; that's not allowed. Imagine what would happen: you keep adding and adding and adding and adding, since every element that you encounter you add - and again, and again and again.