File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StackOverflowError in TREESET Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StackOverflowError in TREESET" Watch "StackOverflowError in TREESET" New topic
Author

StackOverflowError in TREESET

Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634



Getting following error:
lang.StackOverflowError


what's wrong with the code ?


OCPJP 6.0 93%
OCPJWCD 5.0 98%
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9319
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

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

Joined: Aug 02, 2006
Posts: 46
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

Joined: Aug 03, 2008
Posts: 9319
    
  17

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...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: StackOverflowError in TREESET