2015-11-14 88 views
1

我有两个对象。Java对象包含对方

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

回答

2

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

编辑

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

将成为

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

,它会使你的期望。

最后的推荐。 使用child1.parents == parents而不是child1.parents.equals(parents),因为你愿意compare instances of objects(实际上它会有相同的结果,因为你没有重写equals方法)。

+0

对不起,我真的不明白你想说什么。也许包含一些代码?换句话说,你的意思是我只需要将相应的引用添加到'child1'和'child2'? –