• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compareTo method doubt

 
Pooja Oza
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Ryan Beckett
Ranch Hand
Posts: 192
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic