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.
When you do your
toString(), you call thetoString()of the children. No problem here except that you call thetoString()of the parent in here. Which will call thetoString()of the children, etc.Nice infinite loop.
The best way to get rid of it is to change your
toString()method into :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
NullPointerExceptionif it is.Resources :
On the same topic :