July 2, 2005
Generics Wildcards for Dummies
When you have a class
Fruit and a subclass
Cherry you might be surprised that in Java a
List<Cherry> is not an instance of
The reason for this is that
List<Cherry> does not extend the interface of
List<Fruit>, but makes it more narrow. Normally you can do all the things with an subclass instance that you can with an superclass instance, and then some. This is not the case here: You can add a
Banana to a
List<Fruit>, but not to a
List<Cherry>. Therefore you cannot treat a list of cherries as a list of fruits because someone might try to stuff in a banana.
"But wait!", you'll say. "I can write
List<? extends Fruit> instead!". The answer is yes... and no. While the bounded wildcard
? extends Fruit lets you view a list of cherries as a list of fruits, it is not the same as
List<Fruit>. For instance, you cannot add any
Fruit to a
List<? extends Fruit>, because Java cannot resolve whether it might actually be looking at a
List<Cherry>, which can only add cherries.
What we learned today: Generics make a great tool for more type safety, but for heavy use... bring a gun.