Search code examples
javacasting

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


I was going through https://www.tutorialspoint.com/java/java_hashmap_class.htm . 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)i.next();
8           System.out.print(me.getKey() + ": ");
9            System.out.println(me.getValue());
10        }

I was wondering that in line 7 the coder has done i.next() 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. i.next() is saved to Object variable before type casting to Map.Entry

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

    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, i.next() 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!