所以我问了一个与此类似的问题,但我认为我得到的答案与我想要做的事情不符。
假设我有这门课:
Java 代码
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;
}
}
并且在驱动程序类中以这种方式初始化子部分......
Section aSection = new Section();
aMainSection.get(0).aChildSection.add(aSection);
本质上,有人可以告诉我如何在节类中添加一个方法,该方法从“aChildSection”的数组列表返回父项吗?
最佳答案
添加构造函数
private final Section parent;
public Section(Section parent) {
this.parent = parent;
}
public Section getParent() {
return parent;
}
当您添加 child 时
Section aSection = new Section(aMainSection.get(0));
aMainSection.get(0).aChildSection.add(aSection);
关于java - 创建引用父数组列表的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6652153/