aspose file tools*
The moose likes Beginning Java and the fly likes compareTo() and sort() 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 » Java » Beginning Java
Bookmark "compareTo() and sort()" Watch "compareTo() and sort()" New topic
Author

compareTo() and sort()

geet kaur
Ranch Hand

Joined: Sep 03, 2008
Posts: 78
guys i know that we have to implement the comparable interface if we want to use the sort() method generally....in any class....
but the point is i am not able to get how does the sort() and compareTo() methods work...i mean how sorting is getting done???
please help
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40041
    
  28
For compareTo() go to the API documentation for the Comparable<T> interface, and it tells you what you have to implement.

For sorting, many methods use a version of recursive merge sort with omission of already-sorted subsets. Merge sort has the advantage of being stable (it doesn't swap round two objects with the same value) whereas the faster quicksort might swap them round. That means you can sort on name, then age, and the names will remain in order for the same age. For primitives, it doesn't matter whether the sorting is "stable" so they use quicksort.

You can Google for merge sort or sorting algorithms; this is a nice link with animations!
geet kaur
Ranch Hand

Joined: Sep 03, 2008
Posts: 78
when we call sort() method then the compareTo() method is automatically getiing called?
Rusty Shackleford
Ranch Hand

Joined: Jan 03, 2006
Posts: 490
Yes.

The best way to learn about sorting is to write your own search routines. That way you will get first hand knowledge instead of trying to figure out what is going on in a black box.

Merge sort and quick sort are fairly complicated algorithms. Start simple, bubble sort is a quick and easy algorithm to implement. It should be very clear how compareTo gets used. It will also start you down the important path of time complexity.

http://en.wikipedia.org/wiki/Bubble_sort
[ September 13, 2008: Message edited by: Rusty Shackleford ]

"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40041
    
  28
Originally posted by geet kaur:
when we call sort() method then the compareTo() method is automatically getiing called?
Yes. Unless you have passed a Comparator object, in which case the Comparator's method, which I think is called compare(), is called.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: compareTo() and sort()