aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes compareTo method doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "compareTo method doubt" Watch "compareTo method doubt" New topic
Author

compareTo method doubt

Pooja Oza
Greenhorn

Joined: Apr 01, 2009
Posts: 21
hi,

could someone please explain me why the compareTo method returns a string array in reverse order? how does a compareTo method and compare method work in java?

It returns a -ve integer, zero or a +ve integer based on the second argument less than first argument, both second and first arguments are equal, and second argument is greater than the first argument.

What is the integer value in case of -ve integer and +ve integer, and how does it compare the whole string array, and how would it sort................ please help me with it.


Please explain me with an example.

Also how is compare method related to the equals method and hashcode method?



Thanks,

Pooja Oza
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18997
    
  40

What is the integer value in case of -ve integer and +ve integer, and how does it compare the whole string array, and how would it sort................ please help me with it.


It doesn't matter what the value is that is returned -- all the sorting algorithm does is check whether the response is positive, negative, or zero. This is why certain classes -- such as for the Integer, Short, Byte, etc. -- just takes a difference. As depending on whether it is greater, less, or equal will generate a negative, positive, or zero difference.

As for strings, the difference is only done for the first character, and returned if it is positive or negative. If zero, then the comparison moves to the next character.


As for how it will sort, think about it... With the ability to recognize which item should come first, you have the ability to create a sorting program. The actual algorithm itself is different for different sorting techniques, but the dependency on the ability to compare is common.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ryan Beckett
Ranch Hand

Joined: Feb 22, 2009
Posts: 192
Comparable.compareTo arranges elements in their natural order. If you've overridden compareTo incorrectly, like return 1 instead of -1 and vice versa, then that would yield the reverse of what you expected. I don't see how that could happen when your dealing with Strings because the String class is final.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: compareTo method doubt