Psychology, asked by ᏢerfectlyShine, 13 hours ago

Difference between comparator and comparable with an example?​

Answers

Answered by pavanisimha1
22

Answer;

Difference Between Comparable and ComparatorMethod of SortingComparable

It uses the compareTo() function for sorting. This is the only method present in the Comparable sorting interface. 

compareTo(Object O) takes as argument an object and compares it to another of the same type. If an object is a string, you can only compare it to another object of the same type. The same is the case with an int object and so on. compareTo() returns a negative, positive or zero integer value based on the result of the sorting. 

Comparator

There are two methods to sort elements in Comparator: compare() and equals(). 

compare(Object O1, Object O2) takes into account two arguments as input and provides the desired output. It returns an integer to indicate how the first argument comares with the second. 

If O1 is less than O2, it returns a negative integer.

If O1 is greater than O2, it will return a positive integer.

If O1 is equal to O2, it returns 0.

equals(Object) takes into account an object as input and compares it to the comparator. It returns True if the Object is equal to the Comparator. It also ensures that the order does not change. 

Package Used

Package UsedComparable

It exists in the java.lang package of Java. 

Comparator

It exists in the java.util package of Java

Hello

Answered by theMYSTERYboy
3

Answer:

Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price. The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc.

Similar questions