The following code snippet throws the error: " Generic array creation" despite not having any generic instances within the Node class. However, if i declare the private class Node as static , the error goes away. Why is the static keyword important here?
public class SeperateChainingST<Key, Value>{
private int M =97;
private Node[] st = new Node[M];
private class Node{
Object key;
Object val;
Node next;
}
}
Node
is a non-static nested class. That means it is an inner class, and it is within the scope of the type parameters Key
and Value
of its outer class.
When you simply write the type Node
without any explicitly qualification inside SeperateChainingST
, it is implicitly qualified as SeperateChainingST<Key, Value>.Node
. This is a parameterized type (it has the type parameters Key
and Value
), even though you do not "see" them when writing Node
.
As you know, you cannot use array creation expression with a component type that is a parameterized type:
new HashMap<Key, Value>[5]
So you cannot do
new Node[5] // which is equivalent to
new SeperateChainingST<Key, Value>.Node[5]
But, as you may also know, array creation expression can be used with a component type that is a raw type, or a type that is parameterized with all wildcards:
new HashMap[5]
new HashMap<?,?>[5]
We can do it similarly here, except how do you get the raw type of the inner class Node
? It is not just Node
, as we have found. Instead, you must explicitly qualify it with the raw type of the outer class:
new SeperateChainingST.Node[5]
or with the all-wildcards way:
new SeperateChainingST<?,?>.Node[5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With