I am trying to make a method call like this,
public class GenericsTest<T> {
public static <T> Map<String, T> createMap(Class<? extends Map<String, T>> clazz) {
return null;
}
public static void main(String[] argv) {
Map<String, Integer> result = createMap(TreeMap.class);
}
}
But I am getting this error,
<T>createMap(java.lang.Class<? extends java.util.Map<java.lang.String,T>>) in test.GenericsTest<T> cannot be applied to (java.lang.Class<java.util.TreeMap>)
How to fix this problem?
This will appropriately print out 1. The implementation of the method is most likely
A better implementation of their API would be for them to ask you for the type,
T, and for them to give back aMapof their choosing instead of asking you for all of the details. Otherwise, as long as they are not filling in theMapwith any data, you can instantiate aMapwith the generic type argument yourself like so:You can then access that without a warning:
There’s really no reason for them to ask you for the
Classtype of yourMapexcept to give you back an exact match to the implementation (e.g., if you stick in aHashMap, then you will get back aHashMap, and if you stick in aTreeMap, then you will get back aTreeMap). However, I suspect that theTreeMapwill lose anyComparatorthat it was constructed with, and since that is an immutable (final) field ofTreeMap, then you cannot fix that; that means that theMapis not the same in that case, nor is it likely to be what you want.If they are filling in the
Mapwith data, then it makes even less sense. You could always pass in an instance of aMapto fill, or have them return aMapthat you can simply wrap (e.g.,new TreeMap<String, Integer>(instance);), and they should know whichMapoffers the most utility to the data.