为什么我得到StackOverflowError

jai*_*jai 11 java stack-overflow

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);
    }
Run Code Online (Sandbox Code Playgroud)

System.out.println正在生成StackOverflowError.

Col*_*ert 17

当你做你的时toString(),你打电话toString()给孩子.这里没问题,除了你toString()在这里打电话给父母.哪个会叫toString()孩子们等等

好的无限循环.

摆脱它的最好方法是将您的toString()方法更改为:

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

这样您就不会打印parentCategory而只打印它的名称,没有无限循环,没有StackOverflowError.

编辑:正如Bolo所说,你需要检查parentCategory是否为空,NullPointerException如果是,你可能会有.


资源:

在同一主题上: