• Post Reply Bookmark Topic Watch Topic
  • New Topic

how compareTo works  RSS feed

 
Rich Stepanski
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an object that has an index field and overrides the compareTo method. I can sort lists of these objects by that field.

When a list of these objects are sorted - how is the compareTo method called? Does every object simply compare itself to the next object in the list?

Depending on the answer to the above questions. Would it be possible to increment the parameter object's index field in the case of equality, so that when a duplicate index occurs the rest of the list's indexes are incremented? Sorry if thats vague. Thanks
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are many different recipes or algorithms that can be used to sort data. Some of the best known ones include the quicksort, Shell sort, heapsort, bubble sort, and selection sort. Most of Java's sorting methods use either quicksort or a modified merge sort. These are all things you can google to learn more about -- they're more complex than I can quickly describe here. Most of these techniques go to great lengths to minimize the number of comparisons -- sorting badly can be slow, and sorting well can be orders of magnitude faster.

Anyway, in general, you can't count on compareTo being called on the elements of an array or collection in any kind of regular order, or even on it being called on every element of the collection. I think, therefore, that the answer to your question (which I have to confess to not understanding, really) is "no".
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given that you can't be sure of the order in which elements are compared, it would be quite unpredictable to change the key by which they're sorted while sorting.

And no, if I understand you correctly, changing the index during sorting wouldn't result in resortnig or reindexing automatically. The sort routine would have no idea that you've change index values.
 
Rich Stepanski
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks. wishful thinking.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To add my own two cents, you can create your own algorithm that does this. I'm not exactly sure how useful it would be, but it's definitely do-able. There's nothing stopping you from calling compareTo() with your own code.

Layne
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!