为什么我收到 StackOverflowError

2024-02-24

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);
    }

The System.out.println正在生成StackOverflowError.


当你做你的toString(),你调用toString()孩子们的。这里没有问题,除了你打电话toString()这里的家长的。这将调用toString()孩子的情况等等

不错的无限循环。

摆脱它的最好方法就是改变你的toString()方法变为:

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

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

EDIT:正如 Bolo 下面所说,您需要检查parentCategory 是否不为空,您可能有一个NullPointerException如果是。


资源 :

  • Javadoc-StackOverflowError http://download.oracle.com/javase/6/docs/api/java/lang/StackOverflowError.html

关于同一主题:

  • java 中的 toString() https://stackoverflow.com/questions/1161228/tostring-in-java
  • Java 后缀计算器中的 StackOverFlowError https://stackoverflow.com/questions/2420323/stackoverflowerror-in-java-postfix-calculator
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我收到 StackOverflowError 的相关文章

随机推荐