How does compiler understand the key and value part of an object during casting?

I was going through .
It gives following code

1       // Get a set of the entries
2       Set set = hm.entrySet();

3       // Get an iterator
4       Iterator i = set.iterator();

5       // Display elements
6       while(i.hasNext()) {
7           Map.Entry me = (Map.Entry);
8           System.out.print(me.getKey() + ": ");
9            System.out.println(me.getValue());
10        }

I was wondering that in line 7 the coder has done which returns java.lang.Object which has been cast to Map.Entry type.Remember in line 7 me variable has pointer to the keys of map that had been defined in earlier lines.
In line 9 we call me.getValue() ,so how does jvm know that a particular value is associated with a particular key?

>Solution :

For easy understanding I have updated the code. is saved to Object variable before type casting to Map.Entry

while(i.hasNext()) {
         Object obj =;
         Map.Entry me = (Map.Entry)obj;
         System.out.print(me.getKey() + ": ");

From the below image captured in debug mode, you can see obj contains key-value before type casting.

enter image description here

To sum up, is returning a Map.Entry but we are storing it in an Object Class reference variable because java allows super class reference variable to hold the sub class object and Object class is super class to all.

Why typecasting? because we can’t invoke sub class methods on a super class variable.

If you want the iterator to return Map.Entry without type casting, declare Iterator as Map.Entry Iterator like this Iterator<Map.Entry> i. Happy learning!

Leave a Reply