这是我在main方法中尝试的内容。 (父节点指向自身并且排名为0.)
public static void main(String[] args) {
DisjointSet x = new DisjointSet();
**Node<T> parent = new Node<T>(parent, 0);**
}
以下是我的错误消息:
错误:无法从静态上下文引用非静态类型变量
错误:无法从静态上下文引用非静态类型变量
在等号的每一侧看起来像T的一个错误。
答案 0 :(得分:0)
错误是因为您正在从静态方法
中访问非静态实例变量界面的所有成员字段默认为public
,static
和final
。
由于内部界面默认为static
,因此您无法从T
字段或方法引用static
。
T 实际上与一个类的实例相关联,如果它与一个static
字段或与类关联的方法相关联那么它就没有任何意义
您可以使用信息创建一个类:
public class MyTreeNode<T>{
public T data = null;
public MyTreeNode parent = null;
public MyTreeNode(T data) {
this.data = data;
}
public void addChild(MyTreeNode child) {
child.setParent(this);
this.children.add(child);
}
public void addChild(T data) {
MyTreeNode<T> newChild = new MyTreeNode<>(data);
newChild.setParent(this);
children.add(newChild);
}
public void addChildren(List<MyTreeNode> children) {
for(MyTreeNode t : children) {
t.setParent(this);
}
this.children.addAll(children);
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
以及主要的例子:
MyTreeNode<String> root = new MyTreeNode<>("Root");
MyTreeNode<String> child1 = new MyTreeNode<>("Child1");
child1.addChild("Grandchild1");
child1.addChild("Grandchild2");
MyTreeNode<String> child2 = new MyTreeNode<>("Child2");
child2.addChild("Grandchild3");
root.addChild(child1);
root.addChild(child2);
root.addChild("Child3");
root.addChildren(Arrays.asList(
new MyTreeNode<>("Child4"),
new MyTreeNode<>("Child5"),
new MyTreeNode<>("Child6")
));
for(MyTreeNode node : root.getChildren()) {
System.out.println(node.getData());
}