Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static nested class?

Tags:

java

I have a sample code for tries.The code seems have no compile errors. Why does it use static nested class node? when I delete static in Node nested class and compile, the error shows create generic array in private Node[] next = new Node[R];. What on earth happened?

public class TrieST<Value> {
    private static final int R = 256;        // extended ASCII


    private Node root;      // root of trie
    private int N;          // number of keys in trie

    // R-way trie node
    private static class Node {
        private Object val;
        private Node[] next = new Node[R];
    }


    public TrieST() {
    }
}
like image 268
Peterxwl Avatar asked Oct 20 '22 17:10

Peterxwl


1 Answers

Assuming that in your code snippet you are using a non-static inner class instead of a static nested class like this: private class Node, in that case, you will be trying to instantiate an Array which is not possible, we can't instantiate an Array in a generic class, because generics doesn't have any information regarding their type at runtime, while arrays creation expression specifies the element type.

So, the reason why using a Static Nested Class compiled, is that such classes are considered as a "top-level" class (in terms of behavior):

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

Now, let's take all of this into consideration, and come back to the exact error displayed by the compiler:

Cannot create a generic array of TrieST<Value>.Node

That means that the type of the array you want to create is TrieST<Value>.Node whose runtime's type is not known, thus different types may be inserted into the next array. More clear and well explained examples could be found in Cannot Create Arrays of Parameterized Types

Whereas, a static Nested class is not behaving as an inner class of TrieST<Value> , thus instiating an array inside Node will not be illegal as it's not of the type TrieST<Value>.Node, its of the type Node (like if it's a top-level class) .

like image 80
Tarik Avatar answered Nov 15 '22 04:11

Tarik