This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Christophe Verré wrote:Another problem is that in doSomethingListMap, I want to put values (which extend SuperClass) in the Map. For example, map.put("aa", new ChildOne()); The compiler doesn't let me do that.
That's because the compiler won't allow you to add elements to a collection that uses an extends bounded wildcard, it becomes read-only for type-safety reasons.
Jelle Klap wrote:That's because the compiler won't allow you to add elements to a collection that uses an extends bounded wildcard, it becomes read-only for type-safety reasons.
"? super SuperClass": the ? is SuperClass or any super type (e.g. Object), so you can add anything that IS-A SuperClass. You don't know what it contains, so you can only retrieve elements as Object without casting.
"? extends SuperClass": the ? is SuperClass or any sub type. Since you don't know which type, you cannot add anything. You know that everything it contains IS-A SuperClass so you can retrieve elements as SuperClass without casting.
So basically, if you need to add elements to a List or Map, "? super SuperType" is required. If you also need to retrieve elements as SuperType there is no other option than use "SuperType" itself.