从嵌套列表对象

时间:2016-01-02 10:07:24

标签: java algorithm tree

我有以下课程:

  public class  MyObject {
  String name;
  List<MyObject> myObjectsList;// it contains nested MyObject references sometimes also in cyclic manner. 
}

在我的Main课程中,我填写了一个列表List<MyObject>
此列表中的对象必须以树状结构打印。
我可以使用哪种算法为了实现这个目标?

1 个答案:

答案 0 :(得分:1)

向您的班级添加打印方法。示例方法

public void print(int level)
{
    // print own name
    String branch = "|";
    for (int i = 0; i < level; i++)
    {
        branch += "-";
    }
    System.out.println(branch + name);

    // print names from list
    if (myObjectsList != null)
    {
        for (MyObject m : myObjectsList)
        {
            m.print(level+1);
        }
    }
}

测试

public static void main(String[] args)
{
    MyObject myObj = new MyObject();
    myObj.name = "Name00";
    myObj.myObjectsList = new ArrayList<MyObject>();

    MyObject tmp1;
    MyObject tmp2;

    tmp1 = new MyObject();
    tmp1.name = "Name10";
    myObj.myObjectsList.add(tmp1);

    tmp1.myObjectsList = new ArrayList<MyObject>();
    tmp2 = new MyObject();
    tmp2.name = "Name20";
    tmp1.myObjectsList.add(tmp2);

    tmp2 = new MyObject();
    tmp2.name = "Name21";
    tmp1.myObjectsList.add(tmp2);

    tmp1 = new MyObject();
    tmp1.name = "Name11";
    myObj.myObjectsList.add(tmp1);

    tmp1 = new MyObject();
    tmp1.name = "Name12";
    myObj.myObjectsList.add(tmp1);

    myObj.print(0);
}

结果

|Name00
|-Name10
|--Name20
|--Name21
|-Name11
|-Name12

现在您可以按照自己想要的方式进行修改