Static nested class inside a parameterized class

I was looking at the Java code implementing the binary search tree presented here and I thought it would be better if the inner class Node

actually turned into a static nested class. However, adding the keyword static

in front (I thought I could do this, since the inner class doesn't actually use an instance of the enclosing class - the one I can get in the inner class Node

like BST.this

that which is related to it) resulted in numerous errors that weren't extremely helpful.

As far as I know, java.util.LinkedList

things like that have also used static nested classes to define the nodes stored internally and are parameterized as well (and of course no problem). Anyone want to clarify?

Thank.

+3


source to share


1 answer


If you make an inner class static

, you will lose the type parameters of the surrounding class. Node

does not have access to Key

and Value

, since it is no longer associated with the instance BST

. You can fix this by adding type parameters to Node

too:

private class Node<NodeKey extends Comparable<NodeKey>, NodeValue> {
    private NodeKey key;           // sorted by key
    private NodeValue val;         // associated data
    private Node<NodeKey, NodeValue> left, right;  // left and right subtrees
    private int N;             // number of nodes in subtree

    public Node(NodeKey key, NodeValue val, int N) {
        this.key = key;
        this.val = val;
        this.N = N;
    }
}

      



And replacing every appearance Node

withNode<Key, Value>

+6


source







All Articles