我有一个类版本,它包含自己的列表对象,现在我希望解析递归列表,并将其放在一个列表中。
这是我的课:
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
这是一个简单的Traversal示例,您可以在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);
}
}
}
您可以尝试以下操作:
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
的所有子元素,并递归地将它们的每个子元素添加到一个大列表中。您最初只需要用根元素调用它一次。
我不知道你到底想要什么:把树中的所有项目都放在列表中打印?将一个项目的子项移动到其父项?
在第一种情况下,你可以向获得它的类添加一个回溯函数:
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;
}
}
}