简体   繁体   中英

Why use comparable and comparator interface

I recently faced and interview where they asked me a question. Why use comparable and comparator interface in java to sort elements of a collection. Why not use a bubble sort directly instead. Forgive me if it is my ignorance, but still give me an answer.

A question such as "why use Comparator or Comparable rather than bubble sort?" really makes no sense. These are not alternatives to each other. Any sorting algorithm (including ones that you code yourself) needs a mechanism for defining the order of the objects. That is what the interfaces do: provide a mechanism for defining an ordering on objects.

If the question is "why use sorting methods built into the JDK rather than write your own?" then the answer is probably fairly obvious: it saves effort and complexity.

If the question is "when should you use Comparable and when should you use Comparator ?" then I would suggest searching for one of the excellent primers on this topic. As a very simplified answer, Comparable is used to define a natural (default) ordering for objects within a class while Comparator is used to define a custom ordering to be passed to a method.

Note also that the Comparator interface has many very powerful methods for defining comparisons. Very little needs to be done manually now. For example, if you have a Person class you can sort a list with code such as:

Collection.sort(personList, Comparator
    .comparingInt(Person::getAge)
    .thenComparing(Person::getSurname));

In my view this code is better than the old mechanism of defining compareTo methods in a class as it hides away the implementation details of returning arbitrary integers representing comparison between fields and makes the intention pretty obvious. In fact it's enough of an improvement on older methods that in my own code I tend to avoid natural orderings altogether unless the class has an inherent obvious order that can be naturally represented as the difference between two integers (eg a class defining temperature or heights).

My feeling is that this is a bit of trick question designed to expose one's knowledge of certain fundamental concepts in the Java language.

A little about Comparable and Comparator . See this

The Comparable interface imposes the natural ordering of an object, through contract of the compareTo() method.

The Comparator interface imposes the total ordering of objects on some collection of objects, through contract of the compare() method.

The Arrays.sort(objectArray) method only works with a collection of objects that implement the Comparable interface, ie have natural ordering.

Stack Post Explaining Total Order vs. Natural Order

If you think about it, if any class implements the Comparable interface then any collection of it's objects can be sorted using Collection.sort() or Arrays.sort() . Any Object will be sorted on the basis of the compareTo method in that class. So, why use a bubble sort? Arrays.sort() uses a quicksort , dual-pivot quicksort , mergesort , or timsort accordingly.

A quick look at the Big-O Cheatsheet reveals 在此处输入图片说明

Notice the bubble sort time. Do you want to use a bubble sort in a worst-case scenario?

在此处输入图片说明

You can use any sorting algorithm of your choice eg bubble, insertion, quicksort with your comparator. It is never a choice between a Comparator implementation and a sorting algorithm.

For elements that have natural ordering eg numbers, strings in a lexical order, a comparator is not required if that order works for you.

What would you do for custom objects or data types that you design? How would you sort two Car objects, two Person objects, two complex numbers and so on? That is where a comparator comes handy eg you can sort a Car based on length, weight, etc that you specify in the comparator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM