Why does the following not compile? The compiler gives an error for the + sign in the print line.
public class Test<T> {
HashMap<Integer,Integer> m = new HashMap<Integer, Integer>();
public static void main(String[] args) {
Integer zero1 = 0;
Integer zero2 = 0;
Test t = new Test();
t.m.put(1,zero1);
t.m.put(2,zero2);
System.out.println(t.m.get(1)+t.m.get(2)==t.m.get(2));
}
}
I understand type erasure, but m is a HashMap<Integer,Integer>, it should not depend on the type <T> at all. Why is the compiler rejecting this? Removing <T> in the first line allows compiling, but I don’t see why this shouldn’t work as well.
Is this a compiler bug or is there any logic behind such behavior?
I don’t have an explanation why, but the behavior does seem to be correct-by-definition.§4.8 “Raw Types” of the Java Language Specification explicitly states that:
In your example, the raw type C is
Test(as opposed toTest<Object>orTest<Integer>or whatnot) and the non-static fieldMism. As a result of the above rule, the type oft.mis the raw typeHashMap, rather thanHashMap<Integer, Integer>, so the return-type oft.m.get(Object)isObjectrather thanInteger.