2013-11-29 2 views
-1

У меня есть один выпуск класса, который содержит объект списка его самого. Теперь я хочу, чтобы этот рекурсивный список получил синтаксический анализ и хотел его в одном списке.Список рекурсивно из класса java

Вот мой класс:

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 детей до п-го уровня? его похожее на дерево. Если объект не имеет дочернего элемента, его значение равно children = null

+0

'Теперь я могу пересекать Список детей до n-го уровня' –

ответ

1

Это просто 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); 
     } 
    } 
} 
-1

Я не знаю, что вам нужно точно: впишите все элементы в дереве, чтобы распечатать его? переместить ребят из одного предмета в родителя?

В первом случае вы можете добавить recoursive функцию к классу, которые приобретают его:

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;       
     } 
    }  
} 
+1

Пожалуйста, не просто код дампа. Было бы гораздо полезнее, если бы вы объяснили, как работает ваш код и почему он работает. – Philipp

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 и рекурсивно добавить каждый из своих дочерних элементов в один большой список. Вам нужно только сначала называть его корневым элементом один раз.

Смежные вопросы