Java – why do I get stackoverflowerror

public class Category {
public class Category {

    private Category parentCategory;
    private Set<Category> childCategories;
    private String name;

    public Category() {
        childCategories = new HashSet<Category>();
    }

    public Category getParentCategory() {
        return parentCategory;
    }

    public void setParentCategory(Category parentCategory) {
        this.parentCategory = parentCategory;
    }

    public Set<Category> getChildCategories() {
        return childCategories;
    }

    public void setChildCategories(Set<Category> childCategories) {
        this.childCategories = childCategories;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

}


public static void main(String[] args) {
        Category books = new Category();
        books.setName("Books");
        books.setParentCategory(null);

        Category novels = new Category();
        novels.setName("Novels");
        novels.setParentCategory(books);

        books.getChildCategories().add(novels);
        //novels.setChildCategories(null);

        System.out.println("Books > " + books);
    }

System. out. Println is generating stackoverflowerror

Solution

When you do tostring(), you call the child of tostring() There is no problem here, except that you call the parent node's tostring() This will call the child of tostring(), etc

Good infinite loop

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

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

In this way, you don't print parentcategory, but only its name. There is no infinite loop and no stackoverflowerror

Editor: as bolo said below, you need to check that the parentcategory is not null. If so, you may have a NullPointerException

resources:

> Javadoc – StackOverflowError

Same subject:

> toString() in java > StackOverFlowError in Java postfix calculator

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>