Сделайте это следующим образом:
import java.util.List;
class Person {
// other fields removed for simplicity
private long id;
private List<Person> persons;
public Person(long id, List<Person> persons) {
this.id = id;
this.persons = persons;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
public List<Person> getPersons() {
return persons;
}
@Override
public String toString() {
return "Person [id=" + id + ", persons=" + persons + "]";
}
public void showAll() {
if (getPersons() == null || getPersons().isEmpty()) {
return;
}
getPersons().get(0).showAll();
System.out.println(getPersons());
}
}
Демонстрация:
public class Main {
public static void main(String[] args) {
Person p1 = new Person(1,List.of(new Person(11, List.of(new Person(111, List.of(new Person(1111, null))),
new Person(112, List.of(new Person(1121, null))),
new Person(113, List.of(new Person(1131, null))))),
new Person(12, List.of(new Person(121, List.of(new Person(1211, null))))),
new Person(13, List.of(new Person(131, List.of(new Person(1311, null)))))));
p1.showAll();
}
}
Вывод:
[Person [id=1111, persons=null]]
[Person [id=111, persons=[Person [id=1111, persons=null]]], Person [id=112, persons=[Person [id=1121, persons=null]]], Person [id=113, persons=[Person [id=1131, persons=null]]]]
[Person [id=11, persons=[Person [id=111, persons=[Person [id=1111, persons=null]]], Person [id=112, persons=[Person [id=1121, persons=null]]], Person [id=113, persons=[Person [id=1131, persons=null]]]]], Person [id=12, persons=[Person [id=121, persons=[Person [id=1211, persons=null]]]]], Person [id=13, persons=[Person [id=131, persons=[Person [id=1311, persons=null]]]]]]