Java - 参考 "to be resolved later"

Java - reference "to be resolved later"

有没有办法在Java中定义"pointers to pointers"?

即我在想这样的事情......

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Test[] test = new Test[20];

        Test t = test[10];

        test[10] = new Test(7);

        System.out.println(t.whatever);
    }
}

class Test{
    public Test(int i){this.whatever = i;}
    Integer whatever;
}

这显然会在 Java 中产生 nullptr 异常。我怎样才能保持更新呢?

即如果这是 C,我可能会这样写:

typedef struct{
    int whatever;
} Test;

int main(int argc, char* argv[]) {

    Test *test = malloc(sizeof(*test) * 20);
    Test *t = &test[10];

    test[10].whatever = 7;
    printf("%d\n",t->whatever);

    return 0;
}

我考虑这样的事情的原因是我试图从文件中解析一棵树,其中每个节点的 children 仅由节点 ID 数组给出。

如果我可以忽略 child 可能已经解析或未解析的事实,并且只指向一个数组条目(对应于 child 的索引),那将很方便nodeID),从而放弃稍后再次遍历所有节点的需要,只是为了插入 child 指针。

我想过创建一个包装器实例数组,然后使用对它们的引用。我可以做得更好吗?

不幸的是,这在 java 中不起作用,因为 java 中不存在指针,唯一的方法是使用对象包装器,例如 AtomicReference

注意: AtomicReference 不适用于这种需要,因为它基于 volatile 变量,这在你的情况,但这是想法。

I'm trying to parse a tree from file where the children to each node are given by an array of node IDs only.

您可以使用 Supplier<T> 实现,该接口的实现能够按需生成 T

final Test[] test = new Test[20];
Supplier<Test> t = () -> test[10];
test[10] = new Test(7);
System.out.println(t.get().whatever); // Prints 7
test[10] = new Test(42);
System.out.println(t.get().whatever); // Prints 42

Demo 1.

如果您无权访问 Java-8,这里是一个使用接口和匿名 class 的实现:

interface ForwardTest {
    Test get();
}

class Main {
    public static void main (String[] args) throws java.lang.Exception {
        final Test[] test = new Test[20];
        ForwardTest t = new ForwardTest() {public Test get() {return test[10];} };
        test[10] = new Test(7);
        System.out.println(t.get().whatever);
    }
}

class Test {
    public Test(int i){this.whatever = i;}
    Integer whatever;
}

Demo 2.