开发者

Referencing Parent Arraylist from Within Arraylist in Java

开发者 https://www.devze.com 2023-03-18 19:19 出处:网络
So I was wondering if it was possible in Java to trace back up an Array List? Meaning, if I have something like:

So I was wondering if it was possible in Java to trace back up an Array List? Meaning, if I have something like:

Section aSection = new Section();
aMainSection.get(0).aChildSection.add(aSection);

Where 'aMainSection' and 'aChildSection' are both Array Lists开发者_Python百科 of type section, can I trace back up from 'aChildSection' to get the values stored in it's parent section 'aMainSection'? Or do I have to create some sort of method within the section class that will do this? Thanks for any help that is offered.


You cannot find all the references to an object from the object itself. You can instead record a "parent" Object in each of the children.

Instead of exposing the raw collections you may way to have custom classes for them.

class ChildSection {
    private final Section parent;
    private final List<Section> sections = new ArraysList<Section>();

    public void add(Section section) {
        sections.add(section);
        section.setParent(parent);
    }
}


No, you can't track upwards with ArrayLists, you will have to add parent references in each Section object.

0

精彩评论

暂无评论...
验证码 换一张
取 消