Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StackOverflowError in TREESET

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Getting following error:
lang.StackOverflowError


what's wrong with the code ?
 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The subject says TreeMap and you are using TreeSet. Anyway, in your compareTo method you are calling the compareTo method again. So there will be infinite calls to compareTo method till the method call stack will overflow resulting in the exception that you got...
 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anyway, in your compareTo method you are calling the compareTo method again. So there will be infinite calls to compareTo method till the method call stack will overflow resulting in the exception that you got...


But,we have to call compareTo within compareTo when Comparable is implemeted.
Then,it means it should always give the StackOverflowError

.
 
Rahul Saple
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But,we have to call compareTo within compareTo when Comparable is implemeted.
Then,it means it should always give the StackOverflowError


Not always do you have to call the compareTo method within the compareTo method.

And even if you do, it isnt the comapreTo method of the current class that should be called since tht would be a recursive call to stack overflow
Rather the call should be a compareTo call of the constituent fields of the current class.

For eg if your code would get modified as below


new Integer(this.field).compareTo(((A)o2).field);

This part of the code wraps the current field object and compares it with the field of the object passed as arguement (using autoboxing).
It does this with the help of the compareTo method of the Integer class and not the current class.
 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically the compareTo method is used to see which object is greater/smaller than the other. Your class is empty, it has no properties so you don't have anything to compare. Rahul's example shows how the compareTo method is used to compare two objects based on their properties...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic