I’m using Eclipse to help me clean up some code to use Java generics properly. Most of the time it’s doing an excellent job of inferring types, but there are some cases where the inferred type has to be as generic as possible: Object. But Eclipse seems to be giving me an option to choose between a type of Object and a type of ‘?’.
So what’s the difference between:
HashMap<String, ?> hash1;
and
HashMap<String, Object> hash2;
An instance of
HashMap<String, String>matchesMap<String, ?>but notMap<String, Object>. Say you want to write a method that accepts maps fromStrings to anything: If you would writeyou can’t supply a
HashMap<String, String>. If you writeit works!
A thing sometimes misunderstood in Java’s generics is that
List<String>is not a subtype ofList<Object>. (ButString[]is in fact a subtype ofObject[], that’s one of the reasons why generics and arrays don’t mix well. (arrays in Java are covariant, generics are not, they are invariant)).Sample: If you’d like to write a method that accepts
Lists ofInputStreams and subtypes ofInputStream, you’d writeBy the way: Joshua Bloch’s Effective Java is an excellent resource when you’d like to understand the not so simple things in Java. (Your question above is also covered very well in the book.)