Generics in HashMap don't seem to be used sequentially

Firstly, new to Generics. Now the question is - in HashMap.java I see the following -

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

Why was this not declared with type parameters?

or

 private V getForNullKey() {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {

Why was a for loop entry entered with type parameters?

Is there a deep concept or just inconsistency available?

+4
source share
1 answer

This is because creating an array of a specific parameterized type is not type safe, and that is why this is not allowed at all.

If you try the code something like this, you get a compiler error:

List<String>[] arr = new ArrayList<String>[10]; // Compiler error: Generic Array creation

, - . , , , ArrayStoreCheck, , , , . , , .

, :

List<String>[] arr = new ArrayList<String>[10];  // Suppose this was valid
Object[] objArr = arr;         // This is valid assignment. A `List[]` is an `Object[]`
objArr[0] = new ArrayList<Integer>();  // There you go. A disaster waiting at runtime.

String str = arr[0].get(0);    // Assigned an `Integer` to a `String`. ClassCastException

, 1- , , , ClassCastException .


- ArrayList - ArrayList<?>, reifiable . , :

List[] arr = new ArrayList[10];
List<?>[] arr2 = new ArrayList<?>[10];

, raw , . , , , . Entry[] Entry<K, V>[].


. :

+7

All Articles