• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regarding the Collections.sort() method  RSS feed

 
Ashwin Rao
Ranch Hand
Posts: 89
C++ Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm a little confused with this method.
Here's my doubt:
Lets suppose that I pass to the sort method a list of 2 objects of the same class (which implements Comparable interface). I read (in head first java) that one object is compared relative to another with one object calling the CompareTo() while the other object being passed as a parameter to the same method.
Now am I safe in assuming that the first object in the list calls the method with the second object being passed as a parameter.
And also how does the CompareTo() work if there are more than 2 elements in the list. Which objcet calls the method and which is passed as a parameter?
Thanks in advance for any help!
 
Paweł Baczyński
Bartender
Posts: 2085
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is something you do not need to worry about.
If you follow the contract of compareTo, you are guaranteed that this method will behave correctly.

If you are curious, you can put some logging inside compareTo and see what happens.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ashwin Rao wrote:And also how does the CompareTo() work if there are more than 2 elements in the list. Which objcet calls the method and which is passed as a parameter?

As Pawel says: DontSweatIt.

For starters, it'll depend on which sort algorithm you use - and AFAIR, the algorithm that Collections.sort() chooses depends on the number of elements being sorted.

It may help to think about it this way:
In order for a sort - ANY sort - to do it's job, it needs to know which order to put any TWO elements it encounters. And that's precisely the information that compareTo() (or Comparator.compare()) provides.

Everything else is up to the sort algorithm itself ... and there are TONS of 'em.

Winston
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can see whether it tells you the algorithm here. Remember: if a new sort algorithm is invented, the algorithm used by that method may change.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!