遍历遍历java类的遍历列表

时间:2013-11-29 12:31:47

标签: java list

我有一个类发布它包含它自己的列表对象现在我想要递归列表来解析并希望它在一个列表中。

这是我的班级:

public class OnTimeNowRelease implements Serializable
{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    int id;
    String name;
    String can_modify;
    String start_date;
    String due_date;
    String velocity_start_date;
    String release_notes;
    String status;
    String is_active;
    String release_type;
    List<OnTimeNowRelease> children ; 
    getter setter//
}

如何将List个孩子追溯到第n级?它就像遍历树。如果对象没有子,则其值为children = null

3 个答案:

答案 0 :(得分:1)

这是一个简单的遍历示例,您主要在LinkedList或Trees中看到。

public void fetchAllChildren(OnTimeNowRelease root, List<OnTimeNowRelease> childList){
    // if the parent is not defined, nothing to do
    if(root == null){
         return;
    }

    //add the parent to the list. Since java is Reference by Value, the list can be used for recursively adding all the descending elements 
    childList.add(root);
    if(root.children !=null && !root.children.isEmpty()){   
         for(OnTimeNowRelease children : root.children){
                //simple recursive solution add all the children and their children and so on....
                fetchAllChildren(root.children, childList);
         }
    }
}

答案 1 :(得分:0)

您可以尝试以下方式:

public List<OnTimeNowRelease> flattenLists(OnTimeNowRelease obj) {
    List<OnTimeNowRelease> result = new ArrayList<OnTimeNowRelease>();
    List<OnTimeNowRelease> children = obj.getChildren(); 
    if (children==null || children.isEmpty()) {
        return result;
    } else {
        for (OnTimeNowRelease child : children) {
            result.addAll(flattenLists(child));
        }
    }
    return result;
}

这将迭代每个List的所有子元素,并递归地将每个子元素添加到一个大列表中。您只需要首先使用根元素调用它一次。

答案 2 :(得分:-1)

我不知道你究竟想要什么:列出树中的所有项目进行打印?将一个项目的孩子移到他的父母那里?

在第一种情况下,您可以向获得它的类添加一个递归函数:

public List<OnTimeNowRelease> obtainDescendants() {
    // create a list for the childs
    List<OnTimeNowRelease> items = new ArrayList<OnTimeNowRelease>();
    // add myself
    items.addAll(this);

    if(children != null) {
        // add my childs and his childs to the list
        for(OnTimeNowRelease child : this.children) {       
            items.addAll( child.obtainDescendants() );
        }
    }

    return items;
}

在秒钟的情况下,您可以执行类似

的操作
public void inherintChilds() {  
    if( children == null) {
        return;
    }    

    for(OnTimeNowRelease child : this.children) {
         if( child.children != null) {      
             // take the childs
             this.children.addAll(child.children);
             // quit to my child
             child.children = null;                        
         }
    }       
}
相关问题