1 import java.util.ArrayList;
 2 
 3 public class Person {
 4     public String name;
 5     public Person superior;     // double linked = both navigation directions
 6     public ArrayList<Person> employees = new ArrayList<>();
 7 
 8     Person(String name, Person superior)
 9     {
10         this.name = name;
11         this.employees = new ArrayList<>();
12         if (superior != null)   // Supererior exists => is not boss
13         {
14             this.superior = superior;
15             superior.employees.add(this);
16         }
17         else
18             this.superior = null;
19     }
20 
21     public String getName() {
22         return name;
23     }
24     public Person getSuperior() {
25         return superior;
26     }
27     public ArrayList<Person> getEmployees() {
28         return employees;
29     }
30 }

 1 public class Main {
 2 
 3     public static void main(String[] args) {
 4         Person p1 = new Person("Boss", null);
 5 
 6         Person p11 = new Person("Head of Department - Purchasing", p1);
 7         Person p111 = new Person("Purchaser A", p11);
 8         Person p112 = new Person("Purchaser B", p11);
 9 
10         Person p12 = new Person("Head of Department - IT", p1);
11         Person p121 = new Person("Programmer", p12);
12         Person p122 = new Person("Administrator", p12);
13 
14         System.out.println("Superiors of: " + p121.getName());
15         Main.showSuperior(p121);
16 
17         System.out.println("\nEmployees of: " + p1.getName() + ": ");
18         Main.showEmployees(p1, 0);
19     }
20 
21 
22     static private void showSuperior(Person p)  // possible without recursion
23     {
24         while(p.getSuperior() != null)
25         {
26             System.out.println(p.getSuperior().getName());
27             p = p.getSuperior();
28         }
29     }
30 
31     static private void showEmployees(Person p, int recDepth)
32     {
33         if (p.getEmployees().size() > 0)
34         {
35             recDepth++;
36             for (Person person: p.getEmployees())
37             {
38                 for (int i = 0; i < recDepth; i++)
39                     System.out.print("\t");
40                 System.out.println(person.getName() + " ");
41                 Main.showEmployees(person, recDepth);  // recursive call
42             }
43         }
44     }
45 }
Last modified: Monday, 20 May 2019, 9:01 AM