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.
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.