java 递归组织部门
时间: 2023-11-04 07:50:08 浏览: 11
下面是一个简单的 Java 递归组织部门的示例代码:
```java
public class Department {
private String name;
private List<Department> subDepartments;
public Department(String name) {
this.name = name;
this.subDepartments = new ArrayList<>();
}
public void addSubDepartment(Department department) {
subDepartments.add(department);
}
public String getName() {
return name;
}
public List<Department> getSubDepartments() {
return subDepartments;
}
public void printDepartments(int level) {
for (int i = 0; i < level; i++) {
System.out.print("-");
}
System.out.println(name);
for (Department subDepartment : subDepartments) {
subDepartment.printDepartments(level + 1);
}
}
}
```
在这个示例中,`Department` 类表示一个部门,它包含一个名称和一个子部门列表。`addSubDepartment` 方法用于向子部门列表中添加新的子部门。`printDepartments` 方法使用递归方式打印出整个部门组织结构,它接受一个参数 `level`,表示当前部门在组织结构中所处的层级,根部门的 `level` 值为 0。
使用示例:
```java
public static void main(String[] args) {
Department root = new Department("公司总部");
Department department1 = new Department("部门1");
Department department11 = new Department("部门1-1");
Department department111 = new Department("部门1-1-1");
department11.addSubDepartment(department111);
department1.addSubDepartment(department11);
Department department2 = new Department("部门2");
Department department21 = new Department("部门2-1");
department2.addSubDepartment(department21);
root.addSubDepartment(department1);
root.addSubDepartment(department2);
root.printDepartments(0);
}
```
输出结果:
```
公司总部
-部门1
--部门1-1
---部门1-1-1
-部门2
--部门2-1
```
阅读全文