首页 > 解决方案 > 二叉树中通用节点的Java数组,无法创建零节点

问题描述

我遇到了与此问题类似的问题: Array of generic nodes Java

然而,使嵌套的 Node 类静态解决了一个问题,但为我创建了另一个问题。我写了一个二叉树,每次节点的指针不应该指向任何东西(例如叶节点的左右指针或根的父指针)时,它实际上指向一个特殊的“nil”节点,其中不包含相关数据。Nil 是二叉树的成员变量。

当我创建一个节点时,构造函数使所有指针都指向 nil。但是,如果我将 Node 类设为静态,以便创建节点数组(我需要为特定方法执行此操作),我会收到每个指针的错误消息“无法对非静态字段进行静态引用零。” 但是,如果我将 nil 更改为静态,我会得到一个错误,上面写着“无法对非静态类型 T 进行静态引用”。(我的节点保存参数化类型对象。)

这是我的节点类:

protected static class Node<T>{
    Node left, right, parent;
    T object;

    protected Node(T x) {
        object= x;
        left= nil;
        right= nil;
        parent= nil;
    }
}

这是 nil 指定和二叉树构造函数,它创建 nil 节点并使其成为根:

protected static Node<T> nil;

public BT() {
    nil= new Node<T>(null);
    root= nil;
}

我如何允许自己创建节点数组而不会遇到这些静态与非静态问题?

标签: javaarraysstaticnodesnon-static

解决方案


First, never use raw generics, so specify <T> on the Node fields:

protected static class Node<T> {
    Node<T> left, right, parent;
    T object;

Next, to initialize nil, you need a difference constructor:

protected Node() {
    left = this;
    right = this;
    parent = this;
}

Now you can initialize nil as a non-static object, to keep type-safety:

protected Node<T> nil = new Node<>();

Though, rather than creating a nil object for every tree, create a static method:

@SuppressWarnings("rawtypes")
private static Node NIL = new Node();

@SuppressWarnings({ "cast", "unchecked" })
protected static <T> Node<T> nil() {
    return (Node<T>) NIL;
}

推荐阅读