Search code examples
javaarraylistparent-childparentbacktrace

Referencing Parent Arraylist from Within Arraylist in Java


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


Solution

  • 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);
        }
    }