Generics in HashMap implementation

后端 未结 3 574
北海茫月
北海茫月 2021-01-26 17:49

In the Java implementation, I found

 transient Entry[] table; 
 which is initiated in constructor as
 table = new Entry[capacity];

I know and u

3条回答
  •  情书的邮戳
    2021-01-26 18:10

    Generics are a compile-time safety. At runtime, the map only know about Objects. This is known as type erasure. To scare you even more, the following code will run without problem:

    Map safeMap = new HashMap<>();
    Map unsafeMap = safeMap;
    unsafeMap.put("hello", "world");
    

    You'll get a warning at compile time, because you're using a raw Map instead of a generic one, but at runtime, no check is done at all, because the map is a good old map able of storing any object. Only the compiler prevents you from adding Strings in a map or integers.

提交回复
热议问题