简体   繁体   中英

Java Objects contain each other

I have two objects.

Child.java

public class Child {
    Parents parents;
}

Parents.java

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

I want them to have each other. For example:

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

However after much thinking, I came to a problem that they cannot seem to have each other at the same time. One of the two children will have an older parent.

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

This will cause the child2.parent.children to not have child1 .

You're working with objects so your variables are actually references. When you assign "parents" as the parent of child1 you're saving a reference, not a value, and vice-versa. So if you make "parents" the parent of "child1" and "child2" both will be referencing the same object. And if you add the back references both childs will still "see" the changes because you're referencing the same objects in memory. I'm I clear? I'm not a native English speaker, sorry!

EDIT

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

would become

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

and it will make what you expect.

A final recomendation. Use child1.parents == parents instead of child1.parents.equals(parents) because you're willing to compare instances of objects (actually it will have the same result because you didn't override the equals method).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM