• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparator  RSS feed

 
Saad Zahoor
Ranch Hand
Posts: 82
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator







  

Question : Why do we use Comparator in Real time . in this code below the class what else can i do ? i mean                             

 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Saad Zahoor wrote:



This is *not* a valid compare() method -- as required by the Comparator class. As described by the JavaDoc, a comparator needs to be transitive -- Or else it will produce different results depending on what elements, and/or the order the sort algorithm uses to compare those elements. Of course, the JavaDoc chosen to use some blah blah math explanation, but that is the jist of it...

Heck, even without the underlying requirement, you are not even following the requirement of the first paragraph as stated in the JavaDoc to be a valid comparator.
JavaDoc compare method wrote:
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Henry  
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm assuming that by "real time" you meant "practical, real-world situations"

Sometimes, natural ordering isn't what we need. Or maybe there is no intuitive natural ordering. If you have a collection of objects that you want to sort in different ways, you can use different comparators to do that, one comparator for each different sorting criteria.

Say you had some objects that had name, color, size, weight, and price attributes. To sort these with Collections.sort(List), the class needs to implement the Comparable interface, which defines the compareTo() method. This will be the class' natural ordering, which you can think of as its default ordering. Say you used the name attribute for natural ordering. So when you sort, these objects will ordered by name in alphabetical order.

What if you wanted to sort in reverse alphabetical order? By color? By weight? Any other way besides name in alphabetical order? If you wanted to use Collections.sort(), you'd have to use the overloaded version that takes a Comparator as its second parameter. The comparator basically encapsulates the logic for determining whether one object should be considered as coming before or after another object in a certain ordering.

See also the tutorial on ordering: https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!