使用递归的arrayList的分层数据。 (JAVA)

时间:2017-12-10 13:42:05

标签: java recursion arraylist

我在员工及其下属的MySQL中有分层数据,如图所示here有一个加入列' managerID'它引用同一列中的员工ID。

我的目标是递归遍历这些数据并将其全部添加到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新手,我调试代码失败了。如果你能指出我的错误,我将非常感激。

1 个答案:

答案 0 :(得分: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();

    }

}

递归中的技巧是每次打印出当前员工,然后打印任何下属,如方法中所示。如果需要,我会留给你提出括号。