2

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?

Mike
  • 47,263
  • 29
  • 113
  • 177
Ascension
  • 2,599
  • 2
  • 15
  • 13
  • 1
    What kind of error specifically? – Arran Mar 05 '13 at 17:29
  • 2
    In an earlier version I'd say it's an autoboxing problem. But Java 6 does support autoboxing. Are you sure it's actually Java 6? – DerMike Mar 05 '13 at 17:31
  • It's because you can't == an object to a primitive. Java7 understands it is an Integer and will auto-unbox it, but Java6 will need you to parametrise the `Entry`. – entonio Mar 05 '13 at 17:32
  • You are not using Generic type while getting Map.Entry .. It should be `Map.Entry e` for version before java version before below 7 – Vishal K Mar 05 '13 at 17:33
  • 1
    The e.getKey return object and compared with 3 without type cast! This works in java 7, but in 6 it give error! – Ascension Mar 05 '13 at 17:34

4 Answers4

2

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

Presumably you need to assign a type to your Entry:

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

There are changes in Java 7 to the generics framework. I am not sure whether that code would, as you suggest, work in Java 7 but I can say that you need to specify the generic types of Entry for it to work in Java 6.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
0

Its a template problem in Java 6 I think.

This fixes it:

public static void printMap(Map obj) {

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

Java 6 doesn't auto pass the arguments from the Map to the Map.Entry

-2

Try this

if (e.getKey().toString().equals("3")) 

I think e.getKey() returns an object and you were comparing it with integer. Either convert it to integer and compare or to String and compare

codingbiz
  • 26,179
  • 8
  • 59
  • 96