【发布时间】:2017-12-10 13:42:04
【问题描述】:
我在 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 新手,但我的代码调试失败。如果您能指出我的错误,我将不胜感激。
【问题讨论】: