Forums Register Login

Comparable & Comparator

+Pie Number of slices to send: Send
How is Comparable different from Comparator?
Also what how do we modify the instances of the class we implement Comparable in?
What do we do when we implement Comparator ?
+Pie Number of slices to send: Send
+Pie Number of slices to send: Send
thanks a lot .
Material of great help.
+Pie Number of slices to send: Send
 

bharat bhasin wrote:How is Comparable different from Comparator?
Also what how do we modify the instances of the class we implement Comparable in?
What do we do when we implement Comparator ?



Hello, bharat

The following table summarizes the differences between the Comparable and Comparator interfaces:

Comparable Interface Comparator Interface

It uses the compareTo() method. It uses the compare() method.
int compare(ObjOne, ObjTwo) int objectOne.compareTo(objectTwo)

It is necessary to modify the class whose instance is A separate class can be created in order to sort instance
going to be sorted.

Only one sort sequence can be created. Many sort sequences can be created.

It is frequently used by the API classes. It it used by third-party classes to sort instances.
+Pie Number of slices to send: Send
 

bharat bhasin wrote:How is Comparable different from Comparator?
Also what how do we modify the instances of the class we implement Comparable in?
What do we do when we implement Comparator ?



The following table summarizes the differences between the Comparable and Comparator interfaces:

Comparable InterfaceComparator Interface
It uses the compareTo() method. <uc:stx>int objectOne.compareTo(objectTwo)</uc:stx>It uses the compare() method. <uc:stx>int compare(ObjOne, ObjTwo)</uc:stx>
It is necessary to modify the class whose instance is going to be sorted.A separate class can be created in order to sort the instances.
Only one sort sequence can be created. Many sort sequences can be created.
It is frequently used by the API classes.It it used by third-party classes to sort instances.
+Pie Number of slices to send: Send
Actually, most of the API classes have overloaded methods / constructors that take a Comparator for custom sorting as well. The TreeMap / TreeSet constructors, Collections.sort and Arrays.sort sure do.
+Pie Number of slices to send: Send
It's the bit about many sort sequences that is the crucial point. You can sort objects on different criteria at different times.
His brain is the size of a cherry pit! About the size of this ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1581 times.
Similar Threads
comparator and comparable interfaces
Reg. Natural ordering
TreeSet - insertion of Objects
array List Program
Comparator & Comparable
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 02:25:40.