SlideShare a Scribd company logo
1 of 15
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

What's hot

Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...Edureka!
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfKnoldus Inc.
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in javasawarkar17
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
What is Interface in Java | How to implement Multiple Inheritance Using Inter...
What is Interface in Java | How to implement Multiple Inheritance Using Inter...What is Interface in Java | How to implement Multiple Inheritance Using Inter...
What is Interface in Java | How to implement Multiple Inheritance Using Inter...Edureka!
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaEdureka!
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksMaulik Shah
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptionsmyrajendra
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 

What's hot (20)

Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 
Java collections
Java collectionsJava collections
Java collections
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
What is Interface in Java | How to implement Multiple Inheritance Using Inter...
What is Interface in Java | How to implement Multiple Inheritance Using Inter...What is Interface in Java | How to implement Multiple Inheritance Using Inter...
What is Interface in Java | How to implement Multiple Inheritance Using Inter...
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Java program structure
Java program structure Java program structure
Java program structure
 
Features of java
Features of javaFeatures of java
Features of java
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 

Viewers also liked

Equals, Hashcode, ToString, Comparable e Comparator
Equals, Hashcode, ToString, Comparable e ComparatorEquals, Hashcode, ToString, Comparable e Comparator
Equals, Hashcode, ToString, Comparable e ComparatorRodrigo Cascarrolho
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVCJohn Lewis
 
Banking Cards And Emv
Banking Cards And EmvBanking Cards And Emv
Banking Cards And EmvKingshuk1
 
Spring Mvc,Java, Spring
Spring Mvc,Java, SpringSpring Mvc,Java, Spring
Spring Mvc,Java, Springifnu bima
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 

Viewers also liked (9)

Equals, Hashcode, ToString, Comparable e Comparator
Equals, Hashcode, ToString, Comparable e ComparatorEquals, Hashcode, ToString, Comparable e Comparator
Equals, Hashcode, ToString, Comparable e Comparator
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
 
Spring Mvc
Spring MvcSpring Mvc
Spring Mvc
 
Banking Cards And Emv
Banking Cards And EmvBanking Cards And Emv
Banking Cards And Emv
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Spring Mvc,Java, Spring
Spring Mvc,Java, SpringSpring Mvc,Java, Spring
Spring Mvc,Java, Spring
 
EMV chip cards
EMV chip cardsEMV chip cards
EMV chip cards
 
HSM Basic Training
HSM Basic TrainingHSM Basic Training
HSM Basic Training
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 

Similar to Comparable and comparator – a detailed discussion

Whats resources compat_contextcompat_and_appcompat
Whats resources compat_contextcompat_and_appcompatWhats resources compat_contextcompat_and_appcompat
Whats resources compat_contextcompat_and_appcompatChang John
 
Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1LK394
 
Visual Programming
Visual ProgrammingVisual Programming
Visual ProgrammingBagzzz
 
COIT20245, 2016 Term One - Page 1 of 9 Assessment detail.docx
COIT20245, 2016 Term One - Page 1 of 9 Assessment detail.docxCOIT20245, 2016 Term One - Page 1 of 9 Assessment detail.docx
COIT20245, 2016 Term One - Page 1 of 9 Assessment detail.docxclarebernice
 
Xamarin.Forms Hands On Lab (Begineer)
Xamarin.Forms Hands On Lab (Begineer)Xamarin.Forms Hands On Lab (Begineer)
Xamarin.Forms Hands On Lab (Begineer)Cheah Eng Soon
 
03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdfssusera587d2
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsPhilip Schwarz
 
Web driver selenium simplified
Web driver selenium simplifiedWeb driver selenium simplified
Web driver selenium simplifiedVikas Singh
 
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...Ahmed Gad
 
Implementing the Adapter Design Pattern
Implementing the Adapter Design PatternImplementing the Adapter Design Pattern
Implementing the Adapter Design PatternProdigyView
 
How to Build a Basic Model with Analytica
How to Build a Basic Model with AnalyticaHow to Build a Basic Model with Analytica
How to Build a Basic Model with AnalyticaTorsten Röhner
 
Evolve Your Code
Evolve Your CodeEvolve Your Code
Evolve Your CodeRookieOne
 
Cis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingCis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingHamad Odhabi
 

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

Whats resources compat_contextcompat_and_appcompat
Whats resources compat_contextcompat_and_appcompatWhats resources compat_contextcompat_and_appcompat
Whats resources compat_contextcompat_and_appcompat
 
Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
 
L9
L9L9
L9
 
Sda 9
Sda   9Sda   9
Sda 9
 
COIT20245, 2016 Term One - Page 1 of 9 Assessment detail.docx
COIT20245, 2016 Term One - Page 1 of 9 Assessment detail.docxCOIT20245, 2016 Term One - Page 1 of 9 Assessment detail.docx
COIT20245, 2016 Term One - Page 1 of 9 Assessment detail.docx
 
Xamarin.Forms Hands On Lab (Begineer)
Xamarin.Forms Hands On Lab (Begineer)Xamarin.Forms Hands On Lab (Begineer)
Xamarin.Forms Hands On Lab (Begineer)
 
csharp.docx
csharp.docxcsharp.docx
csharp.docx
 
03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also Programs
 
Web driver selenium simplified
Web driver selenium simplifiedWeb driver selenium simplified
Web driver selenium simplified
 
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...
 
Design Patern::Adaptor pattern
Design Patern::Adaptor patternDesign Patern::Adaptor pattern
Design Patern::Adaptor pattern
 
AutoMapper
AutoMapperAutoMapper
AutoMapper
 
Implementing the Adapter Design Pattern
Implementing the Adapter Design PatternImplementing the Adapter Design Pattern
Implementing the Adapter Design Pattern
 
How to Build a Basic Model with Analytica
How to Build a Basic Model with AnalyticaHow to Build a Basic Model with Analytica
How to Build a Basic Model with Analytica
 
Evolve Your Code
Evolve Your CodeEvolve Your Code
Evolve Your Code
 
Unit 3 lecture-2
Unit 3 lecture-2Unit 3 lecture-2
Unit 3 lecture-2
 
React
ReactReact
React
 
Cis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingCis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programming
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Recently uploaded (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 

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

  1. 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.
  2. 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.
  3. 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.