Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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;
        }
    }
like image 681
deepak Avatar asked Dec 11 '14 05:12

deepak


1 Answers

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]
like image 195
newacct Avatar answered Oct 18 '22 21:10

newacct