JavaObjects互相牵制

Java Objects contain each other

我有两个objects.

Child.java

public class Child {
    Parents parents;
}

Parents.java

public class Parents {
    ArrayList<Child> children = new ArrayList<Child>();
}

我希望他们拥有彼此。例如:

Foo.java

public class Foo {
    public static void main(String[] args) {
        Child child1 = new Child();
        Child child2 = new Child();
        ArrayList<Child> children_list= new ArrayList<Child>();
        children_list.add(child1).add(child2);
        Parents parents = new Parents();

        for (Child child : children_list) {
            // ...
            // Bind them together
            // ...
        }
        child1.parents.equals(parents); // true
        child2.parents.equals(parents); // true
        // And parents.children is a list containing child1 and child2
    }
}

但是想来想去,我遇到了一个问题,他们似乎不能同时拥有对方。两个 children 之一将有一个较旧的 parent。

parents.children.add(child);
child.parents  = parents;
parents.children.set(parents.children.size() - 1, child);

这将导致 child2.parent.children 没有 child1

您正在使用 object,因此您的变量实际上是引用。当您将 "parents" 指定为 child1 的 parent 时,您保存的是一个引用,而不是一个值,并且 vice-versa。因此,如果您使 "parents" "child1" 和 "child2" 的 parent 都将引用相同的 object。而且,如果您添加反向引用,两个孩子仍将 "see" 更改,因为您在内存中引用相同的 object。 我清楚吗?我的母语不是英语,抱歉!

编辑

// ...
// Bind them together
// ...

会变成

parents.children.add(child);
child.parents = parents;

它会如您所愿。

最后的建议。 使用 child1.parents == parents 而不是 child1.parents.equals(parents) 因为你愿意 compare instances of objects (实际上它会得到相同的结果,因为你没有覆盖 equals 方法)。