为什么我得到StackOverflowError

ai
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正在生成StackOverflowError

科林·赫伯特(Colin Hebert):

当您执行时toString(),您称呼toString()孩子们的。这里没有问题,只不过您toString()在这里调用了父对象。这将称呼toString()孩子,等等。

不错的无限循环。

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

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

这样,您将不打印parentCategory,而仅显示其名称,不显示无限循环,不显示StackOverflowError。

编辑:正如博洛在下面说的那样,您将需要检查parentCategory不为null,NullPointerException如果有则为null


资源:

在同一主题上:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章