【问题标题】:Java Objects contain each otherJava 对象相互包含
【发布时间】:2023-03-03 22:52:01
【问题描述】:

我有两个对象。

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
    }
}

然而经过深思熟虑,我发现他们似乎无法同时拥有彼此的问题。两个孩子中的一个将有一位年长的父母。

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

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

【问题讨论】:

    标签: java reference logic


    【解决方案1】:

    您正在使用对象,因此您的变量实际上是引用。当您将“父母”分配为 child1 的父母时,您正在保存一个引用,而不是一个值,反之亦然。因此,如果您将“parents”设置为“child1”和“child2”的父级,则两者都将引用同一个对象。如果您添加反向引用,两个孩子仍然会“看到”更改,因为您在内存中引用相同的对象。 我清楚了吗?我的母语不是英语,对不起!

    编辑

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

    会变成

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

    它会如你所愿。

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

    【讨论】:

    • 对不起,我不太明白你想说什么。也许包括一些代码?或者换句话说,你的意思是我只需要相应地添加对child1child2的引用?
    猜你喜欢
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2012-01-21
    • 2018-08-30
    相关资源
    最近更新 更多