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?
Test, and istest1aHashMap<Integer,Integer>too?mainmethod does not refer tom, and nothing refers toT. What is the exact compilation error you are getting ... and where?javac -Xlint:unchecked Test.java, I get warnings that the calls toputare unchecked. For some reason, whentbelongs to the raw typeTest, the compiler treatst.mas belonging to the raw typeHashMap.