java - 创建引用父数组列表的方法

标签 java arraylist parent-child parent backtrace

所以我问了一个与此类似的问题,但我认为我得到的答案与我想要做的事情不符。

假设我有这门课:

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/

相关文章:

java - 使用 Java 访问 JavaScript 对象属性

javascript - 根据 Angular 4 中的某些条件,在子级中单击按钮时,从父级中的数组中删除特定的组件实例

sql - 计算顺序事件和序列 SQL 的计数

java - 如何设置评分栏的星形颜色?

java - 如何过滤 OSGi 服务可见性?

java - 如何从自定义 ArrayList 中获取特定条目?

java - Java 中创建数组和数组列表是一回事吗?

java - ArrayList仅重复打印最后一个成员

ruby-on-rails - Rails - 父/子关系

java - 如何使用带有Jersey的JAX-RS处理CORS