This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparable vs Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Comparable vs Comparator" Watch "Comparable vs Comparator" New topic
Author

Comparable vs Comparator

Satyajeet Kadam
Ranch Hand

Joined: Oct 19, 2006
Posts: 202
Comparable vs Comparator

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

2)Only one sort sequence can be created. 2) Many sort sequence can be created.




Q1) I don't understand what these two points 1&2 mean to say in Comparator ?


Example:
Suppose Employee class which implements Comparable interface.It is sorted using empid.To sort it age wise.I have to modify this class so that it can be sorted age wise.

Q1) Does this point 1 means : You have to modify same class again to make it sorted as age wise.

Q2) Please refer Q2 below


Comparable



Comparator

Q1)A separate class can be created in order to sort the instances?
does this point means that each time you have to create different classes for different sorting requirements.



Q2) Many sort sequence can be created?
We are creating different classes for different sorting requirements. so how we can say we can create many sort sequences?What is use of adding new classes each time
as per requirement changes?
so if this is a case, we can create many sort sequences in Comparable as well.We can go on adding new classes each time as per requirement changes?


Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

amolpalekar kadolkar wrote:
Comparable : It is necessary to modify the class whose instance is going to be sorted.
Comparator :1) A separate class can be created in order to sort the instances.


look at the example : http://lkamal.blogspot.com/2008/07/java-sorting-comparator-vs-comparable.html

<edit>I use Comparator rather than Comparable, since you can separate *compare logic* from the class(which instance needs to sort) to other class</edit>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparable vs Comparator
 
Similar Threads
Difference between Comparable and Comparator
Sorting a Vector by a specific language?
Comparator and Comparable
Comparator and Comparable
Comparable & Comparator