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

ODP
(An Extended) Beginners Guide to Object Orientation in PHP
PPTX
Effective Java - Chapter 3: Methods Common to All Objects
PPTX
Advance java session 14
PPT
Effective Java - Methods Common to All Objects
PPT
Ap Power Point Chpt5
PPT
Ap Power Point Chpt6
PPTX
Flyweight Pattern
PPT
Ap Power Point Chpt8
(An Extended) Beginners Guide to Object Orientation in PHP
Effective Java - Chapter 3: Methods Common to All Objects
Advance java session 14
Effective Java - Methods Common to All Objects
Ap Power Point Chpt5
Ap Power Point Chpt6
Flyweight Pattern
Ap Power Point Chpt8

What's hot (20)

PPT
Ap Power Point Chpt7
PPTX
Hemajava
PPT
Ap Power Point Chpt2
PDF
Steering Model Selection with Visual Diagnostics
PPT
Ap Power Point Chpt9
PPTX
Chap5java5th
PPT
Ppt lesson 08
PPT
Ppt lesson 07
PDF
Steering Model Selection with Visual Diagnostics: Women in Analytics 2019
PPT
Ap Power Point Chpt4
PPTX
Indexers in C#
PPTX
Data strucutre basic introduction
PPTX
Introduction basic schema and SQL QUERIES
PPTX
13string in c#
PPTX
Chap4java5th
PDF
Analysing-MMPLs
PPTX
Lec 1.3 Object Oriented Programming
PPTX
Upstate CSCI 200 Java Chapter 8 - Arrays
PPTX
Lesson 11 one dimensional array
PPT
Abstract data types
Ap Power Point Chpt7
Hemajava
Ap Power Point Chpt2
Steering Model Selection with Visual Diagnostics
Ap Power Point Chpt9
Chap5java5th
Ppt lesson 08
Ppt lesson 07
Steering Model Selection with Visual Diagnostics: Women in Analytics 2019
Ap Power Point Chpt4
Indexers in C#
Data strucutre basic introduction
Introduction basic schema and SQL QUERIES
13string in c#
Chap4java5th
Analysing-MMPLs
Lec 1.3 Object Oriented Programming
Upstate CSCI 200 Java Chapter 8 - Arrays
Lesson 11 one dimensional array
Abstract data types
Ad

Similar to Java Comparable and Comparator (20)

DOCX
Comparable vs comparator
DOCX
Comparable vs comparator
PPTX
Unit 3 lecture-2
PDF
Comparable Interface1.Comparable is the interface which is present.pdf
PPTX
Comparable/ Comparator
PPT
04a-compare in java operator collection.ppt
PPT
04a-compare Object orienting programming.ppt
PPTX
Collections - Sorting, Comparing Basics
PPSX
Comparable and comparator – a detailed discussion
PDF
ComparableThis is the interface which is present in java.lang.pac.pdf
PPSX
Collections - Sorting, Comparing Basics
PDF
10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf
PPT
Interfaces .ppt
PPT
Interfaces.ppt
PPTX
Collections
PPTX
Java Comparable Interface Video Tutorial
PPT
Set_TreeSet_etc comparison in java collection.ppt
PDF
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
PPTX
Session 16 - Collections - Sorting, Comparing Basics
PDF
JAVA PROGRAMMING - The Collections Framework
Comparable vs comparator
Comparable vs comparator
Unit 3 lecture-2
Comparable Interface1.Comparable is the interface which is present.pdf
Comparable/ Comparator
04a-compare in java operator collection.ppt
04a-compare Object orienting programming.ppt
Collections - Sorting, Comparing Basics
Comparable and comparator – a detailed discussion
ComparableThis is the interface which is present in java.lang.pac.pdf
Collections - Sorting, Comparing Basics
10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf
Interfaces .ppt
Interfaces.ppt
Collections
Java Comparable Interface Video Tutorial
Set_TreeSet_etc comparison in java collection.ppt
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Session 16 - Collections - Sorting, Comparing Basics
JAVA PROGRAMMING - The Collections Framework
Ad

More from Sujit Kumar (20)

PPTX
Introduction to OOP with java
PPTX
SFDC Database Basics
PPTX
SFDC Database Security
PPTX
SFDC Social Applications
PPTX
SFDC Other Platform Features
PPTX
SFDC Outbound Integrations
PPTX
SFDC Inbound Integrations
PPTX
SFDC UI - Advanced Visualforce
PPTX
SFDC UI - Introduction to Visualforce
PPTX
SFDC Deployments
PPTX
SFDC Batch Apex
PPTX
SFDC Data Loader
PPTX
SFDC Advanced Apex
PPTX
SFDC Introduction to Apex
PPTX
SFDC Database Additional Features
PPTX
Introduction to SalesForce
PPTX
More about java strings - Immutability and String Pool
PPTX
Hibernate First and Second level caches
PPTX
Java equals hashCode Contract
PPTX
Java build tools
Introduction to OOP with java
SFDC Database Basics
SFDC Database Security
SFDC Social Applications
SFDC Other Platform Features
SFDC Outbound Integrations
SFDC Inbound Integrations
SFDC UI - Advanced Visualforce
SFDC UI - Introduction to Visualforce
SFDC Deployments
SFDC Batch Apex
SFDC Data Loader
SFDC Advanced Apex
SFDC Introduction to Apex
SFDC Database Additional Features
Introduction to SalesForce
More about java strings - Immutability and String Pool
Hibernate First and Second level caches
Java equals hashCode Contract
Java build tools

Recently uploaded (20)

PDF
August Patch Tuesday
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Machine learning based COVID-19 study performance prediction
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
TLE Review Electricity (Electricity).pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Tartificialntelligence_presentation.pptx
PPTX
Machine Learning_overview_presentation.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
August Patch Tuesday
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Machine learning based COVID-19 study performance prediction
OMC Textile Division Presentation 2021.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced methodologies resolving dimensionality complications for autism neur...
Reach Out and Touch Someone: Haptics and Empathic Computing
Per capita expenditure prediction using model stacking based on satellite ima...
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Spectral efficient network and resource selection model in 5G networks
TLE Review Electricity (Electricity).pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Assigned Numbers - 2025 - Bluetooth® Document
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Tartificialntelligence_presentation.pptx
Machine Learning_overview_presentation.pptx
Spectroscopy.pptx food analysis technology
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Group 1 Presentation -Planning and Decision Making .pptx

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?