Every time I need to implement a comparator, I get stuck trying to remember when I should return -1 and when 1, and I have to look it up.
I mean, obviously -1 is less, so it implies that first
is less than second
. But whenever I say that to myself, I get that nagging "are you sure?" feeling. I suspect part of my confusion comes from implementing it the other way around whenever I need a descending sort.
What do you use to remember which is which?
Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members.
The method returns a number indicating whether the object being compared is less than, equal to, or greater than the object being passed as an argument.
Java Comparator is an interface for sorting Java objects. Invoked by “java. util. comparator,” Java Comparator compares two Java objects in a “compare(Object 01, Object 02)” format. Using configurable methods, Java Comparator can compare objects to return an integer based on a positive, equal or negative comparison.
Comparable interface can be used to provide single way of sorting whereas Comparator interface is used to provide different ways of sorting. For using Comparable, Class needs to implement it whereas for using Comparator we don't need to make any change in the class.
I use this simple "substraction" mnemonic:
first - second
So, if first
is "less" than second
you'll get negative result, otherwise - positive or zero if they are equal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With