2
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "aaa");
hashMap.put(2, "baa");
hashMap.put(3, "caa");
System.out.println(hashMap.get(false));

Above code compiles and runs fine.. gives output as null.

What I am trying to understand is there any autoboxing happening in-between that i seem to miss. Because if generics are applied at compile time, get method shall not allow us to pass a boolean there.

Thanks

Jens
  • 67,715
  • 15
  • 98
  • 113

4 Answers4

3

The get method of HashMap is defined as public V get(Object arg0) {. That means you can put any object as parameter. That method do not use generics, so the Parameter is not checked by the Compiler.

Here you can find the javadoc.

Jens
  • 67,715
  • 15
  • 98
  • 113
0

The source code of the mao imnplementation is taking Object as parameter, so you basically can pass as param whatever you want...

V get(Object key);

and the HashMap

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

so if you give another instance as parameter the method will return null

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

The signature of get method in public class HashMap<K,V> is

get(Object key)

It isn't generic. So it's not just boolean, you can pass any object and it will give some output (or null if it doesn't exists).


I think you're confusing this signature with

get(K key)

If it was a signature of this kind, then your operation wouldn't be allowed.

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
0

Map.get isn't a generic method. That way it maintains comparability with pre-generics Java. If it were generic, to maintain compatibility would require dropping the old method (because all types would match Object causing ambiguity for the compiler).

Alex Taylor
  • 8,343
  • 4
  • 25
  • 40