• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Comparable, Comparator

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please, explain the difference!
 
Ranch Hand
Posts: 775
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let's say you have a class called Weight, and you want to compare objects of that class (e.g. for sorting).
You have two choices.
1. Weight can implement Comparable.
This means that the Weight class has some default ordering scheme that will be used by any code that cares about ordering (e.g. java.util collections).
2. Some class, not necessarily Weight, can implement Comparator.
This means that you may have many ways of ordering Weights. For example, you can have an IncreasingWeightOrder, DecreasingWeightOrder, etc. You pass objects that implement the interface in various ways to get the effect you want. If you don't pass one of those objects, then the comparator has no impact on anything.
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
http://www.javaranch.com/newsletter/July2002/newsletterjuly2002.jsp#collections
Scroll down to the "Sorting Collections" section.
 
I love a woman who dresses in stainless steel ... and carries tiny ads:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic