为什么我收到 StackOverflowError

发布于 2024-09-16 17:56:43 字数 1493 浏览 6 评论 0原文

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

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 is generating the StackOverflowError.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

ゃ人海孤独症 2024-09-23 17:56:43

当您执行 toString() 时,您会调用子级的 toString()。除了在这里调用父级的 toString() 之外,这里没有问题。这将调用子级的 toString() 等。

很好的无限循环。

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

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

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

编辑:正如 Bolo 下面所说,您需要检查parentCategory 是否不为空,如果是,您可能会遇到NullPointerException


资源:

同一主题:

When you do your toString(), you call the toString() of the children. No problem here except that you call the toString() of the parent in here. Which will call the toString() of the children, etc.

Nice infinite loop.

The best way to get rid of it is to change your toString() method into :

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

This way you don't print the parentCategory but only its name, no infinite loop, no StackOverflowError.

EDIT: As Bolo said below you will need to check that parentCategory is not null, you might have a NullPointerException if it is.


Resources :

On the same topic :

墨离汐 2024-09-23 17:56:43

由于错误是 System.out.println,因此问题必定出在 toString() 中。

问题是,toString() 会打印您使用 toString() 方法打印的对象的父和子 Category 对象。因此,当您打印一个类别时,它会在父级上调用 toString() ,在子级上调用 toString() ,在子级上调用 toString() 。父级对子级调用 toString() ,依此类推,直到堆栈耗尽。

Since the error is the System.out.println the problem must be in the toString().

The problem is that toString() prints both parent and child Category object for the one your printing using their toString() method. So when you print a Category it calls toString() on the parent which calls toString() on the child which calls toString() on the parent which calls toString() on the child and so on until the stack is exhausted.

停滞 2024-09-23 17:56:43

因为每次调用 Category#toString() 都会产生大量其他 toString。请注意,打印 childCategories 会导致打印出每个元素(通过 toString),从而重复许多 toString 方法调用的整个过程。

不仅如此,每个子级都会在其父级上调用 toString,而父级又会在其子级上调用 toString,每个子级都会在父级上调用 toString ,它又对其子级调用 toString ,这......

Because each call to Category#toString() produces a ton of other toStrings. Notice that printing childCategories causes each element to be printed out (via toString), which in turn repeats this entire process of many toString method calls.

Not only that, but each child calls toString on its parent, which in turn calls toString on its children, which each calling toString on the parent, which in turn calls toString on its children, which...

眼泪也成诗 2024-09-23 17:56:43
return "Category [childCategories=" + childCategories + ", name="
                + name + ", parentCategory=" + parentCategory + "]";

您正在使用诸如 parentCategory 之类的实例来连接到您的 toString。它将调用这些实例的 toString 方法。

toString 调用的循环永远不会结束。因为子类别将调用父类别,而父类别将再次调用子类别,所以...

不是说如果您输入: System.out.println(myObject); ,它实际上是: System.out .println(myObject.toString());

return "Category [childCategories=" + childCategories + ", name="
                + name + ", parentCategory=" + parentCategory + "]";

you are using instances like parentCategory to concat to your toString. it will call toString method of these instances.

this loop of toString calls never end. because child Category will call Parent Category and Parent will call Childs again and so...

not that if you put: System.out.println(myObject); it actually is: System.out.println(myObject.toString());

心头的小情儿 2024-09-23 17:56:43

您的 toString() 正在陷入递归混乱。您需要有两个toString();一份给父母,一份给孩子。您的 toString 可能如下所示:

@Override
public String toString() {
     toStringParent(parent);   // This print only parent
     toStringChildren(children);  // This print only children
}

Your toString() is going into recursive tailspin. You need to have two toString(); one for the parent and one for the children. Your toString can look like this :

@Override
public String toString() {
     toStringParent(parent);   // This print only parent
     toStringChildren(children);  // This print only children
}
沙沙粒小 2024-09-23 17:56:43

StackOverflowError 实际上是在构建将传递给 System.out.println 的 String 参数时引发的。

每次连接 StringCategory 时,都会执行 CategorytoString() 方法。问题是 Category 中的 toString() 有点过于冗长。解决此问题的一种方法是仅打印父类别的名称(跳过其父类别和子类别):

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

StackOverflowError is actually raised while building the String argument that would be passed to System.out.println.

Each time you concatenate a String and a Category, the toString() method of Category is executed. The problem is that your toString() in Category is a bit too verbose. One way to fix it is to print only the name of the parent category (skipping it's parent and children):

@Override
public String toString() {
    return "Category [childCategories=" + childCategories + ", name="
            + name + ", parentCategory="
            + ((parentCategory == null) ? null : parentCategory.getName())
            + "]";
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文