2
Most read
3
Most read
4
Most read
The presentation describes in detail the difference between the
interfaces Comparable and Comparator and also define the usages of
both of them. One thing we need to understand is that, they must not
be used interchangeably, they are two distinct interfaces and they have
their own purpose to exist.
Comparable
 You can actually read the comments in the java source code and
understand, but I find it tough for a newbie to understand the java doc
comments. So here it is in the simplest English possible. When we say
Comparable (please note the able in the word), it actually means that the
interface enables or gives the classes (which implements it) the ability to
compare their instances with each other.
 Also, the interface provides a method compareTo which takes a
parameter T and returns an integer. This means that if a class
implements this interface, it has to provide implementation for the
compareTo method as well. Now the logic inside can be
anything, anything at all. You are free to write your own comparison
logic and say how the object makes a comparison with other objects
of the same kin(I say same kind because, its pointless to compare
two things of different kind, something like comparing a train and a
dog might not make sensed).
How to use Comparable?
We define a class, make it implement the Comparable interface
and provide implementation code for the compareTo method.
Below is a class Car and we want the instances of the Car class to be
capable of comparing themselves to each other. There can be more
than one property which might be used for a healthy
comparison, for simplicity we use just one property for now, the
registration number.
Note: Check Source code in notes section.
Consequences of using Comparable
As we saw above we, can use Comparable and make the
instances of our classes comparable, this satisfies the basic need of
comparing two instances of our Car class. Now, here comes the first
shock, what if I wrote this car class, generated a jar out of it, and
sent it across to all the programmers to use this in their Code?
Consequences of using Comparable Contd..
Everyone includes the jar and instantiate my comparable Car
classes and the are happy using it. One of the programmer has a
requirement to compare the car objects on the basis of the color
code and not the registrationNumber. What is the solution?
Solving the problem – multiple flavors of comparison
 Write his/her own Car class, make it implement the Comparable
interface and provide implementation code to the compareTo
method to compare the color codes instead of registrationNumber.
 Extend our Car class to something like MySpecialCar extends
Car and override the compareTo method to compare the color
codes.
If you think you have solved the problem, then sorry to disappoint
you, this brings in another case, suppose the same programmer wants
to compare the cars based on registration number in one part of
his/her code and do the comparison based on color codes in other part
of the code.
Is it OK?
Now either there has to be one instance of Car and one instance
of MySpecialCar to represent just one car so that both the parts of the
code can use their comparable instances.
How to use Comparator?
Now that we know, the problem which arises with usage of
Comparable, we can effectively understand the reason Comparator
is used. The Comparator is not related to our Car object at all, if we
want to Compare our Car objects, we really don’t need the Car
object to implement Comparator.
It is something like this, you tell me that you want to compare
two Car objects on the basis of registrationNumber and I create a
RegistrationNumberComparator class which will extend the
Comparator interface and give you an instance of my
RegistrationNumberComparator class, which is a comparator ( an
object which is specialized in comparing two cars based on their
registrationNumber).
Now the second need might arise to compare based on the color
codes and I create a ColorCodeComparator class which will extend the
Comparator interface and the comparing logic would be to compare
the color codes.
The method compare(T a, T b) is the method of the Comparator
interface which accepts two parameters, a and b ,where a has to be
compared to b. The comparison logic is whatever you write in the
implementation.
Note: Check Source code in notes section.
Usage
Mostly we need comparison when there is a need of storing the objects
in some ordered fashion in a Collection.
Comparisons are also required while sorting and while implementing
certain data structures.
So you can always pass the desired Comparator to the Collection you
are trying to use.
It’s up to the user’s choice, how to use the Comparator classes he/she
created as a part of the above exercise.
The Debate
The big debate is, if the Comparator interface is so easy and flexible to
use, then why use Comparable which has almost no flexibility and the
classes cannot be re-used as is, if they implement Comparable.
We can see it very clearly, the restrictions imposed by the Comparable
objects help us in restricting the way how objects are compared by
default. So, I am sure it is clear to all the readers that Comparable is
necessary. To elaborate it, what if I don’t want anyone else to compare
the objects I created in any fashion other than I wish.
The Debate
There are several such examples, for e.g.: you would never want an
Integer to be compared to another by there phonetics(how they
sound), you will always want it to be compared by their size.
Yes you guessed it right, all the final classes must implement the
Comparable interface, to ensure that they are not mis-compared in
any code using them. I always advocate using Comparator until you
are trying to make a class final. Few of them are, String, Integer, Byte
etc.
External Resources
This presentation is a part of TechieMe , you can get more in
detail information there.
You can alternatively join the FB Group and FB Page to get
updates on newer topics.

More Related Content

PPTX
Comparable/ Comparator
PPTX
Relational Database Design
ODP
ER Model in DBMS
PPTX
Er diagram
PPTX
Chapter-7 Relational Calculus
PPTX
String, string builder, string buffer
PPTX
Difference between association, aggregation and composition
Comparable/ Comparator
Relational Database Design
ER Model in DBMS
Er diagram
Chapter-7 Relational Calculus
String, string builder, string buffer
Difference between association, aggregation and composition

What's hot (20)

PPTX
Data Types, Variables, and Operators
PPSX
Data Types & Variables in JAVA
PDF
Dbms 8: Enhanced ER Model
PPT
Java buzzwords
PPTX
Data types in java
PPT
ER-Model-ER Diagram
PPTX
Ado.Net Tutorial
PPTX
Acid properties
PPT
Lecture 01 introduction to database
PPTX
DEFINE FRAME AND FRAME SET WITH A EXAMPLE
PPSX
ADO.NET
PPT
15. Transactions in DBMS
PPT
Homework solutionsch8
PPT
Chapter10 conceptual data modeling
DOCX
Unix lab manual
PPTX
Chapter-4 Enhanced ER Model
PPTX
Css selectors
PPSX
DISE - Database Concepts
PPTX
Types of Drivers in JDBC
Data Types, Variables, and Operators
Data Types & Variables in JAVA
Dbms 8: Enhanced ER Model
Java buzzwords
Data types in java
ER-Model-ER Diagram
Ado.Net Tutorial
Acid properties
Lecture 01 introduction to database
DEFINE FRAME AND FRAME SET WITH A EXAMPLE
ADO.NET
15. Transactions in DBMS
Homework solutionsch8
Chapter10 conceptual data modeling
Unix lab manual
Chapter-4 Enhanced ER Model
Css selectors
DISE - Database Concepts
Types of Drivers in JDBC
Ad

Viewers also liked (9)

PPTX
Equals, Hashcode, ToString, Comparable e Comparator
ODP
Spring Portlet MVC
PDF
Spring Mvc
PDF
Banking Cards And Emv
PDF
Java Collections Tutorials
ODP
Spring Mvc,Java, Spring
PPTX
EMV chip cards
PPTX
HSM Basic Training
ODP
Java Spring MVC Framework with AngularJS by Google and HTML5
Equals, Hashcode, ToString, Comparable e Comparator
Spring Portlet MVC
Spring Mvc
Banking Cards And Emv
Java Collections Tutorials
Spring Mvc,Java, Spring
EMV chip cards
HSM Basic Training
Java Spring MVC Framework with AngularJS by Google and HTML5
Ad

Similar to Comparable and comparator – a detailed discussion (20)

DOCX
Comparable vs comparator
DOCX
Comparable vs comparator
PPTX
Java Comparable and Comparator
PPTX
Java Comparable Interface Video Tutorial
PPT
04a-compare Object orienting programming.ppt
PPT
04a-compare in java operator collection.ppt
PPTX
Collections
PPTX
Review Session and Attending Java Interviews
PPTX
Unit 3 lecture-2
PDF
Comparable Interface1.Comparable is the interface which is present.pdf
PPT
02-OOP with Java.ppt
PPT
025466482929 -OOP with Java Development Kit.ppt
PDF
10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf
PPTX
Object Oriented Programming Concepts
PPTX
Objects and classes in OO Programming concepts
PPT
Java oops PPT
PPT
ABAP Object oriented concepts
PPTX
Session 18 - Review Session and Attending Java Interviews
PDF
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
PPT
Object concepts
Comparable vs comparator
Comparable vs comparator
Java Comparable and Comparator
Java Comparable Interface Video Tutorial
04a-compare Object orienting programming.ppt
04a-compare in java operator collection.ppt
Collections
Review Session and Attending Java Interviews
Unit 3 lecture-2
Comparable Interface1.Comparable is the interface which is present.pdf
02-OOP with Java.ppt
025466482929 -OOP with Java Development Kit.ppt
10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf
Object Oriented Programming Concepts
Objects and classes in OO Programming concepts
Java oops PPT
ABAP Object oriented concepts
Session 18 - Review Session and Attending Java Interviews
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Object concepts

Recently uploaded (20)

PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
HVAC Specification 2024 according to central public works department
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
My India Quiz Book_20210205121199924.pdf
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
Hazard Identification & Risk Assessment .pdf
PPTX
Computer Architecture Input Output Memory.pptx
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
HVAC Specification 2024 according to central public works department
Cambridge-Practice-Tests-for-IELTS-12.docx
LDMMIA Reiki Yoga Finals Review Spring Summer
B.Sc. DS Unit 2 Software Engineering.pptx
Unit 4 Computer Architecture Multicore Processor.pptx
AI-driven educational solutions for real-life interventions in the Philippine...
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
My India Quiz Book_20210205121199924.pdf
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
Weekly quiz Compilation Jan -July 25.pdf
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
Hazard Identification & Risk Assessment .pdf
Computer Architecture Input Output Memory.pptx

Comparable and comparator – a detailed discussion

  • 1. The presentation describes in detail the difference between the interfaces Comparable and Comparator and also define the usages of both of them. One thing we need to understand is that, they must not be used interchangeably, they are two distinct interfaces and they have their own purpose to exist.
  • 2. Comparable  You can actually read the comments in the java source code and understand, but I find it tough for a newbie to understand the java doc comments. So here it is in the simplest English possible. When we say Comparable (please note the able in the word), it actually means that the interface enables or gives the classes (which implements it) the ability to compare their instances with each other.
  • 3.  Also, the interface provides a method compareTo which takes a parameter T and returns an integer. This means that if a class implements this interface, it has to provide implementation for the compareTo method as well. Now the logic inside can be anything, anything at all. You are free to write your own comparison logic and say how the object makes a comparison with other objects of the same kin(I say same kind because, its pointless to compare two things of different kind, something like comparing a train and a dog might not make sensed).
  • 4. How to use Comparable? We define a class, make it implement the Comparable interface and provide implementation code for the compareTo method. Below is a class Car and we want the instances of the Car class to be capable of comparing themselves to each other. There can be more than one property which might be used for a healthy comparison, for simplicity we use just one property for now, the registration number. Note: Check Source code in notes section.
  • 5. Consequences of using Comparable As we saw above we, can use Comparable and make the instances of our classes comparable, this satisfies the basic need of comparing two instances of our Car class. Now, here comes the first shock, what if I wrote this car class, generated a jar out of it, and sent it across to all the programmers to use this in their Code?
  • 6. Consequences of using Comparable Contd.. Everyone includes the jar and instantiate my comparable Car classes and the are happy using it. One of the programmer has a requirement to compare the car objects on the basis of the color code and not the registrationNumber. What is the solution?
  • 7. Solving the problem – multiple flavors of comparison  Write his/her own Car class, make it implement the Comparable interface and provide implementation code to the compareTo method to compare the color codes instead of registrationNumber.  Extend our Car class to something like MySpecialCar extends Car and override the compareTo method to compare the color codes.
  • 8. If you think you have solved the problem, then sorry to disappoint you, this brings in another case, suppose the same programmer wants to compare the cars based on registration number in one part of his/her code and do the comparison based on color codes in other part of the code. Is it OK? Now either there has to be one instance of Car and one instance of MySpecialCar to represent just one car so that both the parts of the code can use their comparable instances.
  • 9. How to use Comparator? Now that we know, the problem which arises with usage of Comparable, we can effectively understand the reason Comparator is used. The Comparator is not related to our Car object at all, if we want to Compare our Car objects, we really don’t need the Car object to implement Comparator.
  • 10. It is something like this, you tell me that you want to compare two Car objects on the basis of registrationNumber and I create a RegistrationNumberComparator class which will extend the Comparator interface and give you an instance of my RegistrationNumberComparator class, which is a comparator ( an object which is specialized in comparing two cars based on their registrationNumber).
  • 11. Now the second need might arise to compare based on the color codes and I create a ColorCodeComparator class which will extend the Comparator interface and the comparing logic would be to compare the color codes. The method compare(T a, T b) is the method of the Comparator interface which accepts two parameters, a and b ,where a has to be compared to b. The comparison logic is whatever you write in the implementation. Note: Check Source code in notes section.
  • 12. Usage Mostly we need comparison when there is a need of storing the objects in some ordered fashion in a Collection. Comparisons are also required while sorting and while implementing certain data structures. So you can always pass the desired Comparator to the Collection you are trying to use. It’s up to the user’s choice, how to use the Comparator classes he/she created as a part of the above exercise.
  • 13. The Debate The big debate is, if the Comparator interface is so easy and flexible to use, then why use Comparable which has almost no flexibility and the classes cannot be re-used as is, if they implement Comparable. We can see it very clearly, the restrictions imposed by the Comparable objects help us in restricting the way how objects are compared by default. So, I am sure it is clear to all the readers that Comparable is necessary. To elaborate it, what if I don’t want anyone else to compare the objects I created in any fashion other than I wish.
  • 14. The Debate There are several such examples, for e.g.: you would never want an Integer to be compared to another by there phonetics(how they sound), you will always want it to be compared by their size. Yes you guessed it right, all the final classes must implement the Comparable interface, to ensure that they are not mis-compared in any code using them. I always advocate using Comparator until you are trying to make a class final. Few of them are, String, Integer, Byte etc.
  • 15. External Resources This presentation is a part of TechieMe , you can get more in detail information there. You can alternatively join the FB Group and FB Page to get updates on newer topics.

Editor's Notes

  • #5: public class Car implements Comparable<Car> {intregistrationNumber; String brand;int color; public intcompareTo(Car o) { if (o.registrationNumber < this.registrationNumber) return 1; else if (o.registrationNumber > this.registrationNumber) return -1; return 0; } public intgetRegistrationNumber() { return registrationNumber; } public void setRegistrationNumber(intregistrationNumber) {this.registrationNumber = registrationNumber; } public String getBrand() { return brand; } public void setBrand(String brand) {this.brand = brand; } public intgetColor() { return color; } public void setColor(int color) {this.color = color; }}The important part in the above code is the compareTo method, it returns 1 if the registrationNumber of this car is greater than the car object passed in the method as parameter. It returns -1 if the situation is reversed and it returns a zero otherwise.
  • #9: You can image what happens if there are four of five criteria to compare. So, lets try to fix this, and you guessed it right, the answer is Comparator.
  • #12: import java.util.Comparator;public class RegistrationNumberComparator implements Comparator<Car>{ public int compare(Car o1, Car o2) { if(o1.getRegistrationNumber() > o2.getRegistrationNumber()) return 1; else if(o1.getRegistrationNumber() < o2.getRegistrationNumber()) return -1; return 0; }}class ColorCodeComparator implements Comparator<Car>{ public int compare(Car o1, Car o2) { if(o1.getColor() > o2.getColor()) return 1; else if(o1.getColor() < o2.getColor()) return -1; return 0; }}Your Car class need not implement the Comparable interface in the above scenario, hence it will not have any compareTo method as well.