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

More Related Content

What's hot

Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7dplunkett
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2dplunkett
 
Steering Model Selection with Visual Diagnostics
Steering Model Selection with Visual DiagnosticsSteering Model Selection with Visual Diagnostics
Steering Model Selection with Visual DiagnosticsMelissa Moody
 
Ap Power Point Chpt9
Ap Power Point Chpt9Ap Power Point Chpt9
Ap Power Point Chpt9dplunkett
 
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 2019Rebecca Bilbro
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Data strucutre basic introduction
Data strucutre basic introductionData strucutre basic introduction
Data strucutre basic introductionmanirajan12
 
Introduction basic schema and SQL QUERIES
Introduction basic schema and SQL QUERIESIntroduction basic schema and SQL QUERIES
Introduction basic schema and SQL QUERIESDHIVYADEVAKI
 
13string in c#
13string in c#13string in c#
13string in c#Sireesh K
 
Analysing-MMPLs
Analysing-MMPLsAnalysing-MMPLs
Analysing-MMPLsmiso_uam
 
Lec 1.3 Object Oriented Programming
Lec 1.3 Object Oriented ProgrammingLec 1.3 Object Oriented Programming
Lec 1.3 Object Oriented ProgrammingBadar Waseer
 
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 - ArraysDanWooster1
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesHoang Nguyen
 

What's hot (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
 

Similar to Java Comparable and Comparator

Comparable vs comparator
Comparable vs comparatorComparable vs comparator
Comparable vs comparatorHome
 
Comparable vs comparator
Comparable vs comparatorComparable vs comparator
Comparable vs comparatorDigvijayKale9
 
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 4DanWooster1
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ ComparatorSean McElrath
 
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.pdfanil0878
 
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
 
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İbrahim Kürce
 
Enumerations in java.pptx
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptxSrizan Pokrel
 
JAVA-PPT'S.pptx
JAVA-PPT'S.pptxJAVA-PPT'S.pptx
JAVA-PPT'S.pptxRaazIndia
 
JAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptxJAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptxKunalYadav65140
 

Similar to 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
 
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
 
JAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptxJAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptx
 

More from Sujit Kumar

Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with javaSujit Kumar
 
SFDC Database Basics
SFDC Database BasicsSFDC Database Basics
SFDC Database BasicsSujit Kumar
 
SFDC Database Security
SFDC Database SecuritySFDC Database Security
SFDC Database SecuritySujit Kumar
 
SFDC Social Applications
SFDC Social ApplicationsSFDC Social Applications
SFDC Social ApplicationsSujit Kumar
 
SFDC Other Platform Features
SFDC Other Platform FeaturesSFDC Other Platform Features
SFDC Other Platform FeaturesSujit Kumar
 
SFDC Outbound Integrations
SFDC Outbound IntegrationsSFDC Outbound Integrations
SFDC Outbound IntegrationsSujit Kumar
 
SFDC Inbound Integrations
SFDC Inbound IntegrationsSFDC Inbound Integrations
SFDC Inbound IntegrationsSujit Kumar
 
SFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSujit Kumar
 
SFDC UI - Introduction to Visualforce
SFDC UI -  Introduction to VisualforceSFDC UI -  Introduction to Visualforce
SFDC UI - Introduction to VisualforceSujit Kumar
 
SFDC Deployments
SFDC DeploymentsSFDC Deployments
SFDC DeploymentsSujit Kumar
 
SFDC Data Loader
SFDC Data LoaderSFDC Data Loader
SFDC Data LoaderSujit Kumar
 
SFDC Advanced Apex
SFDC Advanced Apex SFDC Advanced Apex
SFDC Advanced Apex Sujit Kumar
 
SFDC Introduction to Apex
SFDC Introduction to ApexSFDC Introduction to Apex
SFDC Introduction to ApexSujit Kumar
 
SFDC Database Additional Features
SFDC Database Additional FeaturesSFDC Database Additional Features
SFDC Database Additional FeaturesSujit Kumar
 
Introduction to SalesForce
Introduction to SalesForceIntroduction to SalesForce
Introduction to SalesForceSujit Kumar
 
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 PoolSujit Kumar
 
Hibernate First and Second level caches
Hibernate First and Second level cachesHibernate First and Second level caches
Hibernate First and Second level cachesSujit Kumar
 
Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode ContractSujit Kumar
 
Java build tools
Java build toolsJava build tools
Java build toolsSujit Kumar
 

More from 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
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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 RobisonAnna Loughnan Colquhoun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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...Drew Madelung
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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 Scriptwesley chun
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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...Martijn de Jong
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

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?