Wednesday, October 14, 2009

A tricky thing about generics

I ran into this a couple of times now. When using numbers as keys in maps, you have to be really careful with number literals. Number literals by default compile to be of int primitive type and they can be automatically cast (boxed) to Object as Integers.

Take the code below:

public class Test {

 static Map testMap = new HashMap();
 public static void main(String[] args) {
  testMap.put((long)0, "zero");

Notice the cast to long primitive type, tesMap.put(0, "zero") won't even compile. The unfortunate thing is only that the java.util.Map.get method is not parametrized with the Key class of the Map, so testMap.get(0) compiles without errors, but it returns null.