Creating Method to Reference Parent Array List

So I had asked a question similar to this, but I don’t think the answer I got worked with what I was trying to do.

Say I have this class:

Java Code

public class Section
{
    private String sDocumentTitle;
    private String sHeadingTitle;
    private String sText;
    public ArrayList<Section> aSiblingSection = new ArrayList<Section>();
    public ArrayList<Section> aChildSection = new ArrayList<Section>();
    public ArrayList<image> aImages = new ArrayList<image>();

    public void setName(String docTitle)
    {
        //set passed parameter as name
        sDocumentTitle = docTitle;
    }

    public void addName (String docTitle)
    {
        //adds remaining Title String together
        sDocumentTitle += (" " + docTitle);
    }

    public String getName()
    {
        //return the set name
        return sDocumentTitle;
    }

    public void setSection(String section)
    {
        //set passed parameter as name
        sHeadingTitle = section;
    }

    public void addSection(String section)
    {
        //adds section parts together
        sHeadingTitle += ("" + section);
    }

    public String getSection()
    {
        //return the set name
        return sHeadingTitle;
    }
    public void setText(String text)
    {
        //set passed parameter as name
        sText = text;
    }

    public void addText(String text)
    {
        //adds 
        sText += (" " + text);
    }

    public String getText()
    {
        //return the set name
        return sText;
    }
    public ArrayList getChildSection()
    {
        return aChildSection;
    }
}  

And a child section initialized in this manner in a driver class…

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

Essentially, could someone give me an idea of how I would I add a method in the section class which returns the parents from an array list of ‘aChildSection’?

Answer

Add a constructor

private final Section parent;
public Section(Section parent) {
    this.parent = parent;
}

public Section getParent() {
    return parent;
}

When you add a child

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

Leave a Reply

Your email address will not be published. Required fields are marked *