This question already has answers here:
When should a class be Comparable and/or Comparator?
(11 answers)
Closed 6 years ago.
This question was asked in an interview. The question was why String and other wrapper classes implement Comparable instead of Comparator interface. I tried to explain that Comparator is basically to provide customized sorting and Comparable is for default natural sorting order. Also from design principle perspective, Comparable is tightly coupled and Comparator is loosely coupled. However, I could not clarify why String implemented Comparable instead of Comparator.
Strings implement Comparable because they are things that can be compared. In general, things that implement Comparable tend to have a natural ordering, like you mentioned.
A Comparator is a way of comparing things. When you make a Comparator, you're defining a method with which to compare things. You can make many Comparators on a given type to compare things in different ways.
Related
This question already has answers here:
What sorting algorithm used while overriding compare method of comparator interface?
(2 answers)
Closed 5 years ago.
With regards to both Comparable and Comparator interface in Java, i wanted to ask, what is the sorting technique used internally, and any reason for using the sorting technique in comparison to other sort techniques?
Both Comparable and Comparator are interfaces. All they do is define a way of asking whether one object is greater than, equal to, or less than another.
The interfaces don't enforce what that means -- that's up to the class that implements the interface. So one Comparator<Employee> might say that Adam is "greater than" Bill because A comes before B in the alphabet. Another Comparator<Employee> might say that Bill is "greater than" Adam because Bill has been with the company for longer.
Any sort algorithm needs to be able to compare two items, to know which one should come first in the output. If you wrote a bubble sort, you could use Comparator to compare items.
Java has built-in sorts in a few places, including Arrays.sort(), Collections.sort(), Stream::sorted.
The JavaDoc for Arrays and Collections states that:
The implementation was adapted from Tim Peters's list sort for Python ( TimSort). It uses techiques from Peter McIlroy's "Optimistic Sorting and Information Theoretic Complexity", in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.
That JavaDoc for Stream does not specify the sort method - I suspect this is because implementations are free to vary.
This question already has answers here:
When to use Comparable and Comparator
(19 answers)
Closed 6 years ago.
why there is two interface comparable and comparator in java for sorting the collections?
both are doing the same task it seems... confusion on this sorting technique? Please advise
One might want to sort given objects in other way then the it was defined in the given object (using Comparable), that's why there is Comparator available.
Comparable - used in given class to define the default/natural ordering sorting
Comparator - used by foreign code (e.g. from different library) to sort the data in different way, or to add sorting to class that doesn't define Comparable, or to add different sorting order (e.g. sometimes you might want to sort strings case insensitive and sometimes case sensitive).
This question already has answers here:
When should a class be Comparable and/or Comparator?
(11 answers)
Closed 7 years ago.
Employee ID sort can be done using Comparable also as well as Comparator also but Why we go for Comparable when it comes to ID Sorting and why we go for Comparator when it comes to Name's sorting etc...?? Why can't we use Only Comparator for all the work???
If you want, you can use Comparator only. It allows you to freely define arbitrary ways to order object instances (independent of the object's own implementation).
The idea behind Comparable is that there may be a "natural" way to compare instances of some classes. For example, String can be compared to other Strings (to get lexicographical ordering). The class can then "advertise" this natural ordering and make it conveniently accessible.
I don't know if it makes sense for your Employee class to declare ID ordering "natural". Either way, you can only "promote" one order to be the natural one (and it cannot be changed without changing the implementation and contract of the class, so choose wisely).
Comparable is usually used to define a natural ordering (or you can call it a default ordering) on the instances of the class in which it is implemented.
In your Employee example (which is not detailed enough), I can assume that the employee ID is a unique identifier that identifies each employee, so it makes a good candidate for use in the definition of the natural ordering.
The Comparator interface allows us to implement additional orderings on instances of the Employee class, such as ordering by name, age, etc...
You could use just Comparator, but whenever a class has a natural ordering, it makes sense to implement Comparable, which allows you to use some classes and methods that require ordering (TreeSet, Collections.sort(), etc...) without having to pass a Comparator instance.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java sort problem by two fields
I have user object like
class user
{
String firstName;
String lastName;
}
I have a List which contains these object , I have to sort it by first name and if first name matches the sort only those name by last name .
There are a couple of approaches here.
You can to implement a Comparator, and then use this in the standard Java Collection lib to sort your collection e.g. Collections.sort()
Comparator<MyObject> comparator = ....
Collections.sort(listOfObjects, comparator); // note- will sort in place
An alternative is for your object to implement Comparable. This then introduces a native sort order to your object.
Note that you can implement both approaches simultaneously. The former is useful when you want to implement different sorting strategies (e.g. by name, by date, by size etc.). The latter is useful if you want to make use of the concept of native ordering and the standard sort functions within the Java lib.
Check out the Java tutorial on Object Ordering
If you implement Comparable and use your own compareTo method that does what you need.
Another option is to use a custom Comparator as indicated in many other answers.
A nice article showing both approaches can be found here.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
difference between compare() and compareTo()
Java: What is the difference between implementing Comparable and Comparator?
What are the keys differences between Comparable and Comparator.
and which is preferred over the other in what scenarios?
Thanks
Updated - GOOD LINK WITH EXAMPLE!!
http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html
When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.
A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.
For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.
In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.
Comparator provides a way for you to provide custom comparison logic for types that you have no control over.
Comparable allows you to specify how objects that you are implementing get compared.
Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.
Otherwise you can use Comparable.