Why I’m getting StackOverflowError

When you do your toString(), you call the toString() of the children. No problem here except that you call the toString() of the parent in here. Which will call the toString() of the children, etc.

Nice infinite loop.

The best way to get rid of it is to change your toString() method into :

@Override
public String toString() {
    return "Category [childCategories=" + childCategories + ", name="
            + name + ", parentCategory=" + parentCategory.getName() + "]";
}

This way you don’t print the parentCategory but only its name, no infinite loop, no StackOverflowError.

EDIT: As Bolo said below you will need to check that parentCategory is not null, you might have a NullPointerException if it is.


Resources :

On the same topic :

Leave a Comment