2017-12-10 5 views
0

私は、従業員とその従属部の階層データを示しています(here)。同じ列の従業員IDを参照する結合列 'managerID'があります。(Java)

私の目標は、再帰的にこのデータを通過し、このように見える終わるでしょうArrayListにそれをすべて追加することです:

[Tom [Hanna [George [Chris], Rachel]]] 

しかし、ロジックの問題は私のJava関数であり:

public void getList(String employeeName, ArrayList<Object> arrayList) { 

    // Initialise the arrayList the first time 
    if (arrayList == null) { 
     arrayList = new ArrayList<>(); 
    } 

    // Using the string provided, I have found the employee 
    Employee employee = employeeRepository.findByName(employeeName); 

    // adding employee to the list 
    arrayList.add(employee); 

    // Getting list of employee's subordinates 
    List<Employee> subordinates = employee.getSubordinates(); 

    // Checking if employee has subordinates 
    if (subordinates != null) { 

     // Iterate through each of their subordinates and call recursive function 
     for (int i = 0; i < subordinates.size(); i++) { 
      ArrayList<Object> subOrdinateDetails = new ArrayList<>(); 

      // If the subordinate has subordinates, use recursion 
      if (subordinates.get(i).getSubordinates() != null) { 
       getList(subordinates.get(i).getName(), subordinatesDetails); 
      } 
      // Adding this list to the original arrayList 
      arrayList.add(subOrdinateDetails); 
     } 
     System.out.println(arrayList.toString()); 
    } 
} 

私が上記望んで印刷されない方法の終わりにtoStringメソッド、代わりにそれは印刷します。

[Chris] 
    [George, [Chris]] 
    [Rachel] 
    [Hanna, [George, [Chris]], [Rachel]] 
    [Tom, [Hanna, [George, [Chris]], [Rachel]]] 

それをデバッグしようと、私はそれがここにいたかを理解するために、ArrayListの最初のインデックスを取得しようとしたものの、それが印刷されたものです:

Chris 
George 
Rachel 
Hanna 
Tom 

あなたが言うことができるように、私は、Javaに新しいです、と私私のコードのデバッグに失敗しました。あなたが私の間違いを指摘できるなら、私は非常に感謝します。

答えて

0

このように簡単に行うことができます。

public class Employee { 
    private final String name; 
    private final List<Employee> subordinates; 

    public Employee(String name, List<Employee> subordinates) { 
     super(); 
     this.name = name; 
     this.subordinates = subordinates; 
    } 

    public String getName() { 
     return name; 
    } 

    public List<Employee> getSubordinates() { 
     return subordinates; 
    } 

    public void print() { 
     System.out.println(this.name); 
     this.subordinates.forEach(emp -> { 
      emp.print(); 
     }); 
    } 

} 

public class EmployeeTest { 

    public static void main(String[] args) { 
     Employee chris = new Employee("chris", new ArrayList<>()); 
     Employee george = new Employee("george", Arrays.asList(chris)); 
     Employee rachell = new Employee("rachell", new ArrayList<>()); 
     Employee hannah = new Employee("hannan", Arrays.asList(george, rachell)); 
     Employee tom= new Employee("tom",Arrays.asList(hannah)); 

     tom.print(); 

    } 

} 

再帰でのトリックはそれはあなたがこの方法で見ることができるようにの部下のいずれかを印刷する前に、現在の従業員を出力するたびにあります。私はあなたにそれを必要に応じて括弧を思いつくために残しておきます。

関連する問題