public static void main(String[] args) {
Map<String, Map<Long, List<String>>> map = getHashMap();
}
static <K,V> Map<K,V> getHashMap()
{
return new HashMap<K, V>();
}
I saw a similar code in google guava (as factory methods) for making instances of Hashmap without mentioning the generic types.I don’t understand how the generic is getting inferred by the above program.I mean how can the function getHashMap understand the type of map since i’m not passing any type information to the function.
The
getHashMapfunction does not have to infer the types. It’s at the call site that javac is required by the Java Language Spec to infer that the types agree (15.12.2.7 Inferring Type Arguments Based on Actual Arguments).I believe the current plan is (still) for JDK7 to support the diamond operator, so this sort of thing will work with
newtoo, although with a bit of apparently pointless syntax.