Akash Kaundinya
Akash Kaundinya

Reputation: 109

Looping through Set containing Entry objects

import java.util.*;

public class HelloWorld{

     public static void main(String []args){
        HashMap<Integer,String> h = new HashMap<Integer,String>();
        h.put(100,"Hola");
        h.put(101,"Hello");
        h.put(102,"light");
        System.out.println(h); // {100=Hola, 101=Hello, 102=light}
        Set s = h.entrySet();
        System.out.println(s); // [100=Hola, 101=Hello, 102=light] 
        for(Map.Entry<Integer,String> ent : s)
        {
            System.out.println("Key=" + ent.getKey() + " Value=" + ent.getValue());
        }
     }
}

Compile error

HelloWorld.java:13: error: incompatible types: Object cannot be converted to Entry<Integer,String>                                                                                         
        for(Map.Entry<Integer,String> ent : s)                                                                                                                                             
                                            ^ 

I am trying to print key-value pair for each entry type object in the Set s. But it gives compile time error shown above. But code works fine if I replace "s" with " h.entrySet()" and loops fine..How does using reference to hold "h.entrySet()" cause compile error ?

Upvotes: 0

Views: 55

Answers (1)

rax
rax

Reputation: 34

The line

Set s = h.entrySet();

should be

 Set<Map.Entry<Integer,String>> s = h.entrySet();

because for each loop below doesn't know what type of Set s is ?

This code works:

import java.util.*;

public class HelloWorld{

     public static void main(String []args){
        HashMap<Integer,String> h = new HashMap<Integer,String>();
        h.put(100,"Hola");
        h.put(101,"Hello");
        h.put(102,"light");
        System.out.println(h); // {100=Hola, 101=Hello, 102=light}
        Set<Map.Entry<Integer,String>> s = h.entrySet();
        System.out.println(s); // [100=Hola, 101=Hello, 102=light] 
         for(Map.Entry<Integer,String> ent : s)
        {
            System.out.println("Key=" + ent.getKey() + " Value=" + ent.getValue());
        }
     }
}

Whenever you see

incompatible types: Object cannot be converted to.. error

it means JVM is trying to covert Object type to some other type and it leads to compilation error . Here it's happening in the for loop.

Upvotes: 1

Related Questions