When I assign new value to my binary search tree the same way my input method function do, program report error say cannot be referenced from static context. (this line a.root.left = new Node("dd",22)
say Node is not static
this is my program:
package trylang;
import java.util.Arrays;
public class tryBSTnode<Key extends Comparable<Key>, Value> {
private Node root;
private class Node{
private Key key;
private Value value;
private Node left, right;
public Node(Key key, Value val){
this.key = key;
this.value = val;
}
}
public tryBSTnode(){
}
public void put(Key key, Value val){
root = put(root,key,val);
}
public Node put(Node nd, Key key, Value val){
if (nd == null) return new Node(key, val);
int cmp = key.compareTo(nd.key);
if (cmp>0) nd.right = put(nd.right,key,val);
else if (cmp<0) nd.left = put(nd.left, key, val);
else nd.value = val;
return nd;
}
public static void main(String[] args) {
tryBSTnode<String, Integer> a = new tryBSTnode<String, Integer>();
a.put("aa",20);
a.put("bb",67);
a.put("cc",67);
a.root.left = new Node("dd",22); //this line got problem
}
}
The put method logic is that when node is null, we can assign a new node to it.
public Node put(Node nd, Key key, Value val){
if (nd == null) return new Node(key, val);
int cmp = key.compareTo(nd.key);
if (cmp>0) nd.right = put(nd.right,key,val);
else if (cmp<0) nd.left = put(nd.left, key, val);
else nd.value = val;
return nd;
}
The tree structure would be like root(aa,20)->right(bb,67)->right(cc,67), and run the put method do not meet any error. The left side of root is null. However, when I want to assign a new node to left side of tree, itellij say this line a.root.left = new Node("dd",22)
cannot be referenced from static context. Why this line can work in put method, but have error in the main method?
CodePudding user response:
Node
is an inner class, having a tryBSTNode.this
besides this
, with which it can access members - fields or methods - of a tryBSTNode
object.
As that binding of Node is not intended, make it static:
private static class Node {
Or move the class outside tryBSTNode; you are allowed to have additional non-public classes in one source.
Or make a separate source.
You should have named your main class TryBSTNode
. It also looks a bit like a unit test, Test Driven Development. You might look into that, eventually.
CodePudding user response:
As the error says; you can't access non-static members (Node) from statics context (the main method). Put the Node class out of tryBSTNode class and it works.