Search code examples
javaarraylisttostring

java.lang.StackOverflowError when trying to add the same instance of list multiple times


How to resolve java.lang.StackOverflowError for the following code?

Person.java

import java.util.List;

public class Person {
    private String name;
    private List<Person> children;
    public Person() {
    }
    public Person(String name, List<Person> children) {
        this.name = name;
        this.children = children;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Person> getChildren() {
        return children;
    }
    public void setChildren(List<Person> children) {
        this.children = children;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", children=" + children + "]";
    }
}

TestPerson.java

import java.util.ArrayList;
import java.util.List;

public class TestPerson {
    public static void main(String[] args) {
        List<Person> emptylist = new ArrayList<Person>();
        Person p3 = new Person("X", emptylist);
        Person p2 = new Person("Y", emptylist);
        Person p1 = new Person("Z", emptylist);
        p2.getChildren().add(p3);
        p1.getChildren().add(p2);
        System.out.println(p1);
    }
}

Solution

  • All your Parent instances have the same list of children, since you construct a single ArrayList and use it as the children of all three Person. So you have a recursive data structure. Create a different list for each person.