Ascension Ascension - 1 month ago 8
Java Question

Can anyone explain why this works in java 7 and not java 6?

I'm using this code:

public static void printMap(Map<Integer, String> obj) {
for (Map.Entry e : obj.entrySet()) {
if (e.getKey() == 3) {
System.out.println("OK!");
}
}
}


and it works in Java 7. But in Java 6 it gives an error on the line:

if (e.getKey() == 3) {


Can anyone explain to me why I get this error?

Answer

In java 6, you need to specify the types for your Map.Entry variable

Map.Entry<Integer, String> e : obj.entrySet()

before you compare the key or value of such an Entry. Otherwise the compiler thinks you are doing

if (<object of type Object> == 3) 

which makes no sense to it.

Comments