I was looking at the Java code implementing a binary search tree shown here and I thought that it would be better if the inner class Node was in fact turned into a static nested class. However, adding the static keyword in front (I thought I could do this since the inner class does not in fact anywhere use the instance of the enclosing class -- the one I can access in the Node inner class as BST.this -- that is bound to it) resulted in multiple errors which were not extremely helpful.
As far as I'm aware, java.util.LinkedList and similar also used static nested classes to define the nodes stored inside and are also parameterized (and, of course, work without any problems). Anyone care to elaborate?
Thanks.
If you make the inner class static, you'll lose the type parameters of the surrounding class. Node has no access to Key and Value, since it's no longer associated with a instance of 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 occurence of Node with Node<Key, Value>
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