Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparable, Comparator

 
Chris Cairns
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please, explain the difference!
 
Reid M. Pinchback
Ranch Hand
Posts: 775
  • Mark post as helpful
  • send pies
  • 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.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://www.javaranch.com/newsletter/July2002/newsletterjuly2002.jsp#collections
Scroll down to the "Sorting Collections" section.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic