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>开发者_JAVA百科 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'?
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);
With your model, you can't. Add a parent section:
private Section parent;
and set that for every child session (it will be null in the parent session)
I guess, each section (except the main section) has one parent. The trick is, that a section needs to know it's parent section.
A widely used pattern is to set the parent with the constructor and add some logic to the constructor so that it will register the section as parent's child automatically:
public Section(Section parent) {
this.parent = parent; // remember your parent
parent.addChild(this); // register yourself as your parent's child
}
Then use this code to add a section:
Section mainSection = aMainSection.get(0); // ugly!!
Section section = new Section(mainSection);
Refactoring tip - declare all your fields private and implement getters. Even better if those getters don't return the internal lists but just values from the list.
精彩评论