• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Comparable vs Comparator ??

 
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello all,
Whats the difference between the Comparable interface and the Comparator interface apart from the presence of equalsTo() method and the difference of names (compare() & compareTo()).
What i understand is basically both these interfaces are meant for the same purpose. For instance if i need to sort an Array of Custom Objects i can use any of these interfaces.
Are there any basic differences between these 2 interfaces?
Regards,
Sajee
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A "Comparable" is a thing that can be compared to other Comparables.
A Comparator is a thing that compares objects.
Yes, they're both for sorting and ordering objects in containers, but they express subtly different ways of expressing the problem. Comparable is intrusive -- it requires that the compared objects implement it. Comparator has no such restriction -- it can compare any arbitrary objects it wants to. Two Comparables can be compared in only one way. Many Comparators can be written to compare a given class of objects in different ways.
 
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Ernest.
-siva
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The end of the article has examples of using both.
http://www.javaranch.com/newsletter/July2002/newsletterjuly2002.jsp#collections
 
I can't renounce my name. It's on all my stationery! And hinted in this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic