• Post Reply Bookmark Topic Watch Topic
  • New Topic

difference between comparable and comparator  RSS feed

 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
i'm just wondering what is the purpose of java providing two interfaces Comaprable and Comparator for the same purpose of sorting, although one would have been enough.
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some APIs accept Comparable objects to perform operations on them. Like an enhanced for loop uses Comparable objects and a Arrays.sort can use a Comparator. You use Comparator to define different type of sorts. Each Comparator is a separate class. Your main class in question would implement Comparable. There is usually only one sort order here.
 
Campbell Ritchie
Marshal
Posts: 55793
164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Meyers is right. Comparable allows one to compare two objects with the "natural order or sorting," eg for Person objects by name, whilst a Comparator can be used for other sorting orders, eg by age. One can write Comparator objects for different sorting in different situations.
 
Paul Clapham
Sheriff
Posts: 22527
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another important difference: Comparable is designed to compare "this" to some other object, whereas Comparator is designed to compare any two objects. Hence the operational differences that John Meyers and Campbell Ritchie described.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to add to what has been said, using a Comparator does not require a change to the source code of a class. This is useful in situations where you may not have access to the source code.
 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
thanks to all for your replies...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!