Map<String, Integer> instance = new TreeMap<String, Integer>(); @SuppressWarnings("unchecked") Map<String, Integer> map = createMap((Class<? extends Map<String, Integer>>)instance.getClass()); map.put("x", 1); System.out.println("THIS IS x: " + map.get("x"));
This will print correctly 1. It is most likely that the implementation of the method
try { return clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); }
The best implementation of their APIs would be to ask you to specify a type T , and to return a Map of their choice, instead of asking you for all the details. Otherwise, if they do not populate the Map any data, you can create an instance of Map with the generic type argument as follows:
public static <T> Map<String, T> getMap() { return new TreeMap<String, T>(); }
Then you can access this without warning:
They have no reason to ask you about the Class type of your Map , except to return you an exact match for the implementation (for example, if you enter the HashMap , you will get a HashMap , and if you insert into the TreeMap , you will return to TreeMap ) . However, I suspect that TreeMap will lose any Comparator with which it was created, and since this is an immutable ( final ) TreeMap field, you cannot fix it; this means that Map is not the same in this case, and it is unlikely to be what you want.
If they populate Map data with data, this makes even less sense. You can always pass a Map instance to fill in or return a Map to them that you can simply wrap (for example, new TreeMap<String, Integer>(instance); ), and they should know which Map offers the most utility for the data.