0

だから私はこれに似た質問をしましたが、私がやろうとしていたことで得られた答えはうまくいかなかったと思います.

このクラスがあるとします:

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」の配列リストから親を返すセクション クラスにメソッドを追加する方法を教えてもらえますか?

4

3 に答える 3

2

あなたのモデルでは、できません。親セクションを追加します。

private Section parent;

子セッションごとに設定します(親セッションではnullになります)

于 2011-07-11T15:03:24.163 に答える
2

各セクション (メイン セクションを除く) には1 つの親があると思います。トリックは、セクションがそれが親セクションであることを知る必要があるということです。

広く使用されているパターンは、コンストラクターで親を設定し、コンストラクターにいくつかのロジックを追加して、セクションを親の子として自動的に登録することです。

public Section(Section parent) {
  this.parent = parent;   // remember your parent
  parent.addChild(this);  // register yourself as your parent's child
}

次に、このコードを使用してセクションを追加します。

Section mainSection = aMainSection.get(0);   // ugly!!
Section section = new Section(mainSection);

リファクタリングのヒント- すべてのフィールドをプライベートに宣言し、ゲッターを実装します。それらのゲッターが内部リストを返さず、リストからの値のみを返す場合はさらに良いでしょう。

于 2011-07-11T15:12:48.717 に答える