0

The following code snippet does not produce any exceptions,

import java.util.HashMap;
import java.util.Map;

public class TestMain {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "A");
        map.put(2, "B");
        int a = 1;
        short b = 2;
        System.out.println(map.get(a));
        System.out.println(map.get(b));
    }

}

Output:

A
null

Digging into the source code here https://developer.classpath.org/doc/java/util/HashMap-source.html

 295:   public V get(Object key)
 296:   {
 297:     int idx = hash(key);
 298:     HashEntry<K, V> e = buckets[idx];
 299:     while (e != null)
 300:       {
 301:         if (equals(key, e.key))
 302:           return e.value;
 303:         e = e.next;
 304:       }
 305:     return null;
 306:   }

What might be the reasons for them to not use generics in the function parameter as below, which would produce a compile error on type mismatch,

 295:   public V get(K key)
 296:   {
 297:     int idx = hash(key);
 298:     HashEntry<K, V> e = buckets[idx];
 299:     while (e != null)
 300:       {
 301:         if (equals(key, e.key))
 302:           return e.value;
 303:         e = e.next;
 304:       }
 305:     return null;
 306:   }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Nowa Concordia
  • 709
  • 6
  • 23

0 Answers0