Generics in HashMap implementation

后端 未结 3 531
北海茫月
北海茫月 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:19

    The implementation makes an array of Entry objects of type

    static class Entry implements Map.Entry
    

    without providing generic type parameters (source). This is allowed, but it comes with understanding that the compiler is no longer guarantees type safety. For example, in other places in code you could write

    Entry e = table[bucketIndex];
    

    and the compiler will let you do that. If you know for sure that you always set elements of table[] to null or Entry, then you know that the assignment is correct.

    The reason this works without a problem is that generic types in Java are implemented through type erasure, i.e. there is no difference at runtime between Entry objects Entry and Entry.

提交回复
热议问题