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); }@H_301_4@System.out.println正在生成StackOverflowError.
解决方法
当你做toString()时,你调用toString()的孩子.这里没有问题,除了你在这里调用父节点的toString().这将调用toString()的孩子等
@H_301_4@很好的无限循环.
@H_301_4@摆脱它的最好方法是将你的toString()方法改成:
> StackOverFlowError in Java postfix calculator
@Override public String toString() { return "Category [childCategories=" + childCategories + ",name=" + name + ",parentCategory=" + parentCategory.getName() + "]"; }@H_301_4@这样你不要打印parentCategory,而只打印它的名字,没有无限循环,没有StackOverflowError. @H_301_4@编辑:正如Bolo在下面所说的,你需要检查parentCategory不是null,如果是,那么你可能有一个NullPointerException. @H_301_4@资源: @H_301_4@> @L_301_0@ @H_301_4@同一主题: @H_301_4@> toString() in java
> StackOverFlowError in Java postfix calculator