java – 为什么我要得到StackOverflowError

前端之家收集整理的这篇文章主要介绍了java – 为什么我要得到StackOverflowError前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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.

解决方法

当你做toString()时,你调用toString()的孩子.这里没有问题,除了你在这里调用父节点的toString().这将调用toString()的孩子等

很好的无限循环.

摆脱它的最好方法是将你的toString()方法改成:

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

这样你不要打印parentCategory,而只打印它的名字,没有无限循环,没有StackOverflowError.

编辑:正如Bolo在下面所说的,你需要检查parentCategory不是null,如果是,那么你可能有一个NullPointerException.

资源:

> Javadoc – StackOverflowError

同一主题

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

原文链接:https://www.f2er.com/java/122682.html

猜你在找的Java相关文章