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()的孩子等
很好的无限循环.
@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