У меня есть два объекта.Объекты 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
.
Извините, я не совсем понимаю, что вы пытаетесь сказать. Может быть, есть код? Или, другими словами, вы имеете в виду, что мне просто нужно добавить ссылки соответственно на «child1» и «child2»? –