Java : Comparable vs Comparator [duplicate] - java

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.

Related

Java Collections Sorting Hypothetical

I am currently a computer science major and am taking a course in advanced java programming. My question today is if you have two identical lists, lets call them list1 and list2, and you invoke Collections.sort(list1) and Collections.sort(list2), is it possible for these two lists to be different after invoking this? My textbook says that it is possible, while my professor says it isn't. Can someone please clarify this for me?
If we consider the obvious case such as sorting List<Integer>, then no it's not possible. If you're sorting two identical lists, they should be properly sorted of course.
However since Collections.sort() requires that the objects being sorted are Comparable, you can always implement Comparable poorly. For example you could have compareTo() return a random value (or the time of day, or anything not related to the object actually being sorted), and you wouldn't have any idea how they would be sorted.
Collections.sort() can notice if compareTo() is implemented wrong and will throw an exception saying Comparison method violates its general contract!. However it's not 100% guaranteed to notice this, so technically it is possible to have 2 identical collections sorted in different ways.
As equality is defined by Object.equals(), but comparison is defined by Comparable.compareTo() or Comparator.compare(), like the javadoc says:
It is strongly recommended (though not required) that natural
orderings be consistent with equals.
Otherwise it is possible that equal elements are sorted differently.

Why String implements Comparable and not Comparator interface [duplicate]

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.

why there is two interface comparable and comparator in java for sorting the collections? [duplicate]

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

Use of java.lang.Comparable,when the java.util.Comparator can do the work of Comparable? [duplicate]

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.

use of equals() method in comparator interface?

equals() method is available to all java collection classes from the Object class. This method is also declared in Comparator interface, so what is the purpose of declaring this method in Comparator? in which case is it used and how?
what is the purpose of declaring this method in Comparator?
I think it's the designer's way of highlighting the fact that Comparator.equals() imposes some additional requirements on any classes that implement the interface:
Additionally, this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator. Thus, comp1.equals(comp2) implies that sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for every object reference o1 and o2.
The method can be used to establish whether or not two distinct comparators impose the same order.
I think that the main reason is to make it clear that equals method is for testing the Comparator itself. This is obvious when you think about it, but can I imagine that some people might expect equals(Object) to (somehow) be semantically related to the compare(T, T) method.
It also allows the documentation of some common-sense guidelines for when two comparators could be viewed as equal.
Either way, the presence of the equals(Object) method in the interface is solely for documentation purposes.
From the javadoc
Note that it is always safe not to override Object.equals(Object).
However, overriding this method may, in some cases, improve
performance by allowing programs to determine that two distinct
comparators impose the same order.
The idea is simply to be able to allow you to not sort a collection that has already been sorted by another comparator if you realize that the end result will be the same.
Generally it had little use, but when sorting very large collections it is something you might want to look into.
-when the declaring Comparator is compared to another Object (argument)
It's just an over-ridden form of the Object's equals method to let you know if two objects are of same comparator type.
As per your question I think It is used to compare objects after converting in string.
Object class eqlas methods chek both Object are eqls or not And Competres method chek object data like Hello.eqlas("hello")

Categories