Why do I need to declare a static class private to avoid the "Generic Array Creation" error?

The following code snippet throws an error: "Creating a shared array", despite the absence of any shared instances in the Node class. However, if I declare the private class Node static, the error disappears. 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; } } 
+5
source share
1 answer

Node is a non-static nested class. This means that this is an inner class, and it is within the parameters of the Key and Value its outer class.

When you simply write a Node type without an explicit qualification inside SeperateChainingST , it implicitly qualifies as SeperateChainingST<Key, Value>.Node . This is a parameterized type (it has parameters of type Key and Value ), even if you do not see them when writing Node .

As you know, you cannot use an array creation expression with a component type that is a parameterized type:

 new HashMap<Key, Value>[5] 

So you can not do

 new Node[5] // which is equivalent to new SeperateChainingST<Key, Value>.Node[5] 

But, as you can also know, an array creation expression can be used with a component type, which is a raw type, or a type that is parameterized by all wildcards:

 new HashMap[5] new HashMap<?,?>[5] 

We can do it the same way here, except how do you get the raw type of the inner class Node ? As we already found out, this is not just Node . Instead, you must explicitly specify it with the raw type of the outer class:

 new SeperateChainingST.Node[5] 

or using the all-wildcards method:

 new SeperateChainingST<?,?>.Node[5] 
+5
source

Source: https://habr.com/ru/post/1208781/


All Articles