为什么我得到StackOverflowError [英] Why I'm getting 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()
等。
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.
好的无限循环。
摆脱它的最好方法是将 toString()
方法更改为:
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() + "]";
}
这样你就不打印parentCategory而只打印它的名字,没有无限的循环,没有StackOverflowError。
This way you don't print the parentCategory but only its name, no infinite loop, no StackOverflowError.
编辑:正如Bolo所说,你需要检查parentCategory是否为null,你可能有一个 NullPointerException
如果是。
As Bolo said below you will need to check that parentCategory is not null, you might have a NullPointerException
if it is.
资源:
- Javadoc - StackOverflowError
关于同一主题:
- toString() in java
- StackOverFlowError in Java postfix calculator
这篇关于为什么我得到StackOverflowError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!