加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么我要得到StackOverflowError

发布时间:2020-12-14 05:24:41 所属栏目:Java 来源:网络整理
导读:public class Category { private Category parentCategory; private SetCategory childCategories; private String name; public Category() { childCategories = new HashSetCategory(); } public Category getParentCategory() { return parentCategory;
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读