0

I have trying to use hashmap. I have defined hashmap to take key as integer and value as string.

package hello;

import java.util.HashMap;

public class Recursion {
    

    public static void main(String[] args) {
        HashMap<Integer,String> hash1 = new HashMap<Integer,String>();
        hash1.get(5);                  // return null
        hash1.get("hello");            // return null
     
    }
}

In the above code, hash1.get(5) returns null which is expected. But hash1.get("hello") also returns null and doesn't give any exception even though I am trying to get string key. Any idea on the reason?? I tried to see the implementation of get function. I didn't see any type checking there. So, can I assume that there is no type checking even if I defined the type in the generic.

Can someone please explain this in detail and the reasons for why its not giving any compile-time error.

gaurav bajaj
  • 321
  • 3
  • 4
  • 10
  • 3
    Always do research first. Look at the **signature** of the get() method. It takes **Object**. – GhostCat Oct 19 '20 at 13:20
  • This is definitely not the reply I look forward from someone who has read the whole question. Request to read the whole questions and findings before answering!!!! I have mentioned "I tried to see the implementation of get function. I didn't see any type checking there...." – gaurav bajaj Oct 19 '20 at 16:03
  • 1
    The method does take Object as argument. So there can't be type checking. And note that the duplicate question explains WHY that is. And finally: remember about type erasure. Unless a real class object is passed to some generic class, objects of that generic class do not know at runtime what exact class they were instantiated for! – GhostCat Oct 20 '20 at 05:47

0 Answers0