Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does anyone have a useful mnemonic for implementing Comparator?

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?

like image 692
itsadok Avatar asked Mar 30 '11 13:03

itsadok


People also ask

How is comparator implemented?

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.

What is the comparator method?

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.

What are comparators in coding?

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.

Why do we need a comparator?

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.


1 Answers

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.

like image 114
xappymah Avatar answered Oct 04 '22 17:10

xappymah