SlideShare ist ein Scribd-Unternehmen logo
1 von 10
Java Comparable vs Comparator
Sujit Kumar
Zenolocity LLC © 2013-2023
java.lang.Comparable Interface
• Allows an object of a class to be compared to
objects of the same class using a 1 or more
attributes of the same class.
• compareTo method is the ONLY member of
the Comparable interface. Allows objects of a
class to be sorted by natural ordering.
• Implementing Comparable allows:
• calling Collections.sort & Collections.binarySearch
• calling Arrays.sort and Arrays.binarySearch
• using objects as keys in a TreeMap
• using objects as elements in a TreeSet
compareTo method
• Return value is int, 0 => equal, -ve => less than and +ve
=> greater than
• anticommutation :
x.compareTo(y) = - (y.compareTo(x))
• exception symmetry :
x.compareTo(y) throws exactly the same exceptions
as y.compareTo(x)
• transitivity :
if x.compareTo(y) > 0 and y.compareTo(z) > 0,
then x.compareTo(z) > 0 (and same for less than)
if x.compareTo(y) == 0, then x.compareTo(z) has the same sign
as y.compareTo(z)
Example Implementation of
compareTo
public int compareTo(Employee emp) {
int result = this.id.compareTo(emp.getId());
if (result == 0) {
result = this.age > emp.age ? 1 : this.age < emp.age
? -1 : 0;
}
return result;
}
Performance Considerations
• One can greatly increase the performance
of compareTo by comparing first on attributes
which are most likely to differ.
• Preferable to always sort items in an RDBMS
first using ORDER BY instead of in memory in
java using Comparable.
java.util.Comparator Interface
• public int compare (Object o1, Object o2);
• Logical difference between Comparator and
Comparable is :
Comparator in Java compares any two objects,
while Comparable interface compares the
"this" reference with the object specified.
• Return value semantics is same as the
compareTo method of Comparable interface.
Guidelines on when to use
Comparable and Comparator
• For natural (intuitive) ordering use Comparable. Use
Comparator if you want to have an ordering different
from the natural order. If there is more than one
intuitive comparison possible, use a Comparator.
• Use comparable if class is in your control. Use
Comparator if class is NOT in your control and you cannot
make the class author implement Comparable.
• Comparable should be used when you compare instances
of same class (homogeneous). Comparator can be used
to compare instances of same or different classes
(homogeneous and heterogeneous).
Guidelines (continued…)
• Comparator has a distinct advantage of being
self descriptive. Examples:
• If you are writing Comparator to compare two
Employees based upon the salary then name
that comparator as SalaryComparator.
• If you are writing Comparator to compare two
Employees based upon the age then name
that comparator as AgeComparator.
Examples of Comparator
public static Comparator<Employee> EmployeeAgeComparator
= new Comparator<Employee>() {
public int compare(Employee emp1, Employee emp2) {
return emp1.age.compareTo(emp2);
}
};
public static Comparator<Employee> EmployeeNameComparator
= new Comparator<Employee>() {
public int compare(Employee emp1, Employee emp2) {
return emp1.name.compareTo(emp2)
}
};
How to Remember?
• Am I (this) Comparable to (compareTo) my
friend?
• Can I compare (Comparator) apples to
oranges?

Weitere ähnliche Inhalte

Was ist angesagt?

Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
dplunkett
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
dplunkett
 
Ap Power Point Chpt9
Ap Power Point Chpt9Ap Power Point Chpt9
Ap Power Point Chpt9
dplunkett
 
Steering Model Selection with Visual Diagnostics: Women in Analytics 2019
Steering Model Selection with Visual Diagnostics: Women in Analytics 2019Steering Model Selection with Visual Diagnostics: Women in Analytics 2019
Steering Model Selection with Visual Diagnostics: Women in Analytics 2019
Rebecca Bilbro
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 

Was ist angesagt? (20)

Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
 
Hemajava
HemajavaHemajava
Hemajava
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
Steering Model Selection with Visual Diagnostics
Steering Model Selection with Visual DiagnosticsSteering Model Selection with Visual Diagnostics
Steering Model Selection with Visual Diagnostics
 
Ap Power Point Chpt9
Ap Power Point Chpt9Ap Power Point Chpt9
Ap Power Point Chpt9
 
Chap5java5th
Chap5java5thChap5java5th
Chap5java5th
 
Ppt lesson 08
Ppt lesson 08Ppt lesson 08
Ppt lesson 08
 
Ppt lesson 07
Ppt lesson 07Ppt lesson 07
Ppt lesson 07
 
Steering Model Selection with Visual Diagnostics: Women in Analytics 2019
Steering Model Selection with Visual Diagnostics: Women in Analytics 2019Steering Model Selection with Visual Diagnostics: Women in Analytics 2019
Steering Model Selection with Visual Diagnostics: Women in Analytics 2019
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Indexers in C#
Indexers in C#Indexers in C#
Indexers in C#
 
Data strucutre basic introduction
Data strucutre basic introductionData strucutre basic introduction
Data strucutre basic introduction
 
Introduction basic schema and SQL QUERIES
Introduction basic schema and SQL QUERIESIntroduction basic schema and SQL QUERIES
Introduction basic schema and SQL QUERIES
 
13string in c#
13string in c#13string in c#
13string in c#
 
Chap4java5th
Chap4java5thChap4java5th
Chap4java5th
 
Analysing-MMPLs
Analysing-MMPLsAnalysing-MMPLs
Analysing-MMPLs
 
Lec 1.3 Object Oriented Programming
Lec 1.3 Object Oriented ProgrammingLec 1.3 Object Oriented Programming
Lec 1.3 Object Oriented Programming
 
Upstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - ArraysUpstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - Arrays
 
Lesson 11 one dimensional array
Lesson 11 one dimensional arrayLesson 11 one dimensional array
Lesson 11 one dimensional array
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 

Ähnlich wie Java Comparable and Comparator

Comparable vs comparator
Comparable vs comparatorComparable vs comparator
Comparable vs comparator
DigvijayKale9
 
Java Chapter 05 - Conditions & Loops: part 4
Java Chapter 05 - Conditions & Loops: part 4Java Chapter 05 - Conditions & Loops: part 4
Java Chapter 05 - Conditions & Loops: part 4
DanWooster1
 
ComparableThis is the interface which is present in java.lang.pac.pdf
ComparableThis is the interface which is present in java.lang.pac.pdfComparableThis is the interface which is present in java.lang.pac.pdf
ComparableThis is the interface which is present in java.lang.pac.pdf
anil0878
 
Top 20 Core Java Interview Questions & Answers for Selenium Automation Testin...
Top 20 Core Java Interview Questions & Answers for Selenium Automation Testin...Top 20 Core Java Interview Questions & Answers for Selenium Automation Testin...
Top 20 Core Java Interview Questions & Answers for Selenium Automation Testin...
AnanthReddy38
 

Ähnlich wie Java Comparable and Comparator (20)

Comparable vs comparator
Comparable vs comparatorComparable vs comparator
Comparable vs comparator
 
Comparable vs comparator
Comparable vs comparatorComparable vs comparator
Comparable vs comparator
 
Java Chapter 05 - Conditions & Loops: part 4
Java Chapter 05 - Conditions & Loops: part 4Java Chapter 05 - Conditions & Loops: part 4
Java Chapter 05 - Conditions & Loops: part 4
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Overview of Java
Overview of Java Overview of Java
Overview of Java
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
ComparableThis is the interface which is present in java.lang.pac.pdf
ComparableThis is the interface which is present in java.lang.pac.pdfComparableThis is the interface which is present in java.lang.pac.pdf
ComparableThis is the interface which is present in java.lang.pac.pdf
 
JAVA_1.pptx
JAVA_1.pptxJAVA_1.pptx
JAVA_1.pptx
 
Java
JavaJava
Java
 
Top 20 Core Java Interview Questions & Answers for Selenium Automation Testin...
Top 20 Core Java Interview Questions & Answers for Selenium Automation Testin...Top 20 Core Java Interview Questions & Answers for Selenium Automation Testin...
Top 20 Core Java Interview Questions & Answers for Selenium Automation Testin...
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Hibernate using jpa
Hibernate using jpaHibernate using jpa
Hibernate using jpa
 
Unit 3 lecture-2
Unit 3 lecture-2Unit 3 lecture-2
Unit 3 lecture-2
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
 
java framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxjava framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptx
 
Collections
CollectionsCollections
Collections
 
Unequal Equivalence
Unequal EquivalenceUnequal Equivalence
Unequal Equivalence
 
Enumerations in java.pptx
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptx
 
Java_Interview Qns
Java_Interview QnsJava_Interview Qns
Java_Interview Qns
 
JAVA-PPT'S.pptx
JAVA-PPT'S.pptxJAVA-PPT'S.pptx
JAVA-PPT'S.pptx
 

Mehr von Sujit Kumar

Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode Contract
Sujit Kumar
 
Java build tools
Java build toolsJava build tools
Java build tools
Sujit Kumar
 

Mehr von Sujit Kumar (20)

Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with java
 
SFDC Database Basics
SFDC Database BasicsSFDC Database Basics
SFDC Database Basics
 
SFDC Database Security
SFDC Database SecuritySFDC Database Security
SFDC Database Security
 
SFDC Social Applications
SFDC Social ApplicationsSFDC Social Applications
SFDC Social Applications
 
SFDC Other Platform Features
SFDC Other Platform FeaturesSFDC Other Platform Features
SFDC Other Platform Features
 
SFDC Outbound Integrations
SFDC Outbound IntegrationsSFDC Outbound Integrations
SFDC Outbound Integrations
 
SFDC Inbound Integrations
SFDC Inbound IntegrationsSFDC Inbound Integrations
SFDC Inbound Integrations
 
SFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSFDC UI - Advanced Visualforce
SFDC UI - Advanced Visualforce
 
SFDC UI - Introduction to Visualforce
SFDC UI -  Introduction to VisualforceSFDC UI -  Introduction to Visualforce
SFDC UI - Introduction to Visualforce
 
SFDC Deployments
SFDC DeploymentsSFDC Deployments
SFDC Deployments
 
SFDC Batch Apex
SFDC Batch ApexSFDC Batch Apex
SFDC Batch Apex
 
SFDC Data Loader
SFDC Data LoaderSFDC Data Loader
SFDC Data Loader
 
SFDC Advanced Apex
SFDC Advanced Apex SFDC Advanced Apex
SFDC Advanced Apex
 
SFDC Introduction to Apex
SFDC Introduction to ApexSFDC Introduction to Apex
SFDC Introduction to Apex
 
SFDC Database Additional Features
SFDC Database Additional FeaturesSFDC Database Additional Features
SFDC Database Additional Features
 
Introduction to SalesForce
Introduction to SalesForceIntroduction to SalesForce
Introduction to SalesForce
 
More about java strings - Immutability and String Pool
More about java strings - Immutability and String PoolMore about java strings - Immutability and String Pool
More about java strings - Immutability and String Pool
 
Hibernate First and Second level caches
Hibernate First and Second level cachesHibernate First and Second level caches
Hibernate First and Second level caches
 
Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode Contract
 
Java build tools
Java build toolsJava build tools
Java build tools
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Java Comparable and Comparator

  • 1. Java Comparable vs Comparator Sujit Kumar Zenolocity LLC © 2013-2023
  • 2. java.lang.Comparable Interface • Allows an object of a class to be compared to objects of the same class using a 1 or more attributes of the same class. • compareTo method is the ONLY member of the Comparable interface. Allows objects of a class to be sorted by natural ordering. • Implementing Comparable allows: • calling Collections.sort & Collections.binarySearch • calling Arrays.sort and Arrays.binarySearch • using objects as keys in a TreeMap • using objects as elements in a TreeSet
  • 3. compareTo method • Return value is int, 0 => equal, -ve => less than and +ve => greater than • anticommutation : x.compareTo(y) = - (y.compareTo(x)) • exception symmetry : x.compareTo(y) throws exactly the same exceptions as y.compareTo(x) • transitivity : if x.compareTo(y) > 0 and y.compareTo(z) > 0, then x.compareTo(z) > 0 (and same for less than) if x.compareTo(y) == 0, then x.compareTo(z) has the same sign as y.compareTo(z)
  • 4. Example Implementation of compareTo public int compareTo(Employee emp) { int result = this.id.compareTo(emp.getId()); if (result == 0) { result = this.age > emp.age ? 1 : this.age < emp.age ? -1 : 0; } return result; }
  • 5. Performance Considerations • One can greatly increase the performance of compareTo by comparing first on attributes which are most likely to differ. • Preferable to always sort items in an RDBMS first using ORDER BY instead of in memory in java using Comparable.
  • 6. java.util.Comparator Interface • public int compare (Object o1, Object o2); • Logical difference between Comparator and Comparable is : Comparator in Java compares any two objects, while Comparable interface compares the "this" reference with the object specified. • Return value semantics is same as the compareTo method of Comparable interface.
  • 7. Guidelines on when to use Comparable and Comparator • For natural (intuitive) ordering use Comparable. Use Comparator if you want to have an ordering different from the natural order. If there is more than one intuitive comparison possible, use a Comparator. • Use comparable if class is in your control. Use Comparator if class is NOT in your control and you cannot make the class author implement Comparable. • Comparable should be used when you compare instances of same class (homogeneous). Comparator can be used to compare instances of same or different classes (homogeneous and heterogeneous).
  • 8. Guidelines (continued…) • Comparator has a distinct advantage of being self descriptive. Examples: • If you are writing Comparator to compare two Employees based upon the salary then name that comparator as SalaryComparator. • If you are writing Comparator to compare two Employees based upon the age then name that comparator as AgeComparator.
  • 9. Examples of Comparator public static Comparator<Employee> EmployeeAgeComparator = new Comparator<Employee>() { public int compare(Employee emp1, Employee emp2) { return emp1.age.compareTo(emp2); } }; public static Comparator<Employee> EmployeeNameComparator = new Comparator<Employee>() { public int compare(Employee emp1, Employee emp2) { return emp1.name.compareTo(emp2) } };
  • 10. How to Remember? • Am I (this) Comparable to (compareTo) my friend? • Can I compare (Comparator) apples to oranges?