SlideShare a Scribd company logo
1 of 3
Comparable Vs Comparator
Both are used to sort the objects of the class.
Packages:
Comparable is in: java.lang
Comparator is in: java.util
Syntax:
Interface Comparable<T>
T- the type of object that this object may be compared to
Interface Comparator<T>
T- the type of object that this object may be compared to
Class implementing Comparable interface need to override
int compareTO(T o)
which compares this obj with specified object for order.
Class implementing Comparator interface need to override
int compare(T o1, T o2)
compares its two arguments for order.
boolean equals(Object o)
indicates whether some other object is "equal to" this comparator.

Comparable
When we create list(or array) of object of user defined class, we cannot call
Collection.sort() method to sort object in the list, because they do not have
natural ordering.
To define natural ordering we implement Comparable interface on the Object we
want to compare our class to.
Implementing class must override compareTo(Object o) method
Example:
class Employee implements Comparable<Employee>
{
int id;
String name;
int compareTo(Employee emp)
{
return (this.id<emp.id) ? -1 : (this.id>emp.id) ? 1 : 0;
}
}
When -1: this returned that means: this object’s id is less than emp.id
When 1: this returned that means: this object’s id is greater than emp.id
When 0: both objects are equal.
OR
return this.id.compareTo(emp.id);
This will return result in ascending order.
To print in descending order:
return –this.id.compareTo(emp.id); // - negative sign returns decending

Comparator
The class whose objects to be sorted do not need to implement this interface.
Some third class can implement this interface to sort. E.g.,
EmployeeSortByIdComparator class can implement Comparator interface to sort
collection of employee object by id.
Using Comparator interface, we can write different sorting based on different
attributes of objects to be sorted.
Parameter

Comparable

Comparator

Sorting Logic

Sorting logic must be in same
class whose objects are being
sorted. Hence this is called
natural ordering of objects

Sorting logic is in separate
class. Hence we can write
different sorting based on
different attributes of objects
to be sorted. E.g. Sorting
using id,name etc.

Implementation

Class whose objects to be sorted
must implement this interface.
e.g. Employee class needs to
implement comparable to
collection of country object by id

Sorting method

int compareTo(Object o1)
This method compares this object
with o1 object and returns a
integer. Its value has following
meaning
positive – this object is greater
than o1
zero – this object equals to o1

Class whose objects to be
sorted do not need to
implement this interface.
Some other class can
implement this interface.
E.g.EmployeeSortByIdComparator
class can implement
Comparator interface to sort
collection of country object by
id
int compare(Object o1,Object
o2)
This method compares o1 and
o2 objects. and returns a
integer.Its value has following
meaning.
positive – o1 is greater than
o2
Calling method

negative – this object is less than
o1
Collections.sort(List)
Here objects will be sorted on the
basis of CompareTo method

zero – o1 equals to o2
negative – o1 is less than o1
Collections.sort(List,
Comparator)
Here objects will be sorted on
the basis of Compare method
in Comparator

More Related Content

What's hot

What's hot (19)

Operators in java
Operators in javaOperators in java
Operators in java
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
 
Software Engineering - Module 3: Lesson7
Software Engineering - Module 3: Lesson7Software Engineering - Module 3: Lesson7
Software Engineering - Module 3: Lesson7
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
 
Functions
FunctionsFunctions
Functions
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Generics
GenericsGenerics
Generics
 
Java Generics
Java GenericsJava Generics
Java Generics
 
My c++
My c++My c++
My c++
 
Oops
OopsOops
Oops
 
4. java intro class
4. java intro class4. java intro class
4. java intro class
 
C++
C++C++
C++
 
Type conversions
Type conversionsType conversions
Type conversions
 
Generics C#
Generics C#Generics C#
Generics C#
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
 
Objects and Types C#
Objects and Types C#Objects and Types C#
Objects and Types C#
 

Similar to Comparable vs comparator

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
 
Java Comparable and Comparator
Java Comparable and ComparatorJava Comparable and Comparator
Java Comparable and ComparatorSujit Kumar
 
Number 1 I have completed and number 6 is just uploading I .pdf
Number 1 I have completed and number 6 is just uploading I .pdfNumber 1 I have completed and number 6 is just uploading I .pdf
Number 1 I have completed and number 6 is just uploading I .pdfadvancethchnologies
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual BasicSangeetha Sg
 
Comparable Interface1.Comparable is the interface which is present.pdf
Comparable Interface1.Comparable is the interface which is present.pdfComparable Interface1.Comparable is the interface which is present.pdf
Comparable Interface1.Comparable is the interface which is present.pdfreyazansari001
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.pptVarunP31
 
Kotlin Playground.pptx
Kotlin Playground.pptxKotlin Playground.pptx
Kotlin Playground.pptxGDSCVJTI
 
C++Sortable ObjectsStudy the file Sortable.h. It contains a simp.pdf
C++Sortable ObjectsStudy the file Sortable.h. It contains a simp.pdfC++Sortable ObjectsStudy the file Sortable.h. It contains a simp.pdf
C++Sortable ObjectsStudy the file Sortable.h. It contains a simp.pdfsels6
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in SpringASG
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object ReferencesTareq Hasan
 
PATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and JavaPATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and JavaMichael Heron
 

Similar to Comparable vs comparator (20)

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
 
Unit 3 lecture-2
Unit 3 lecture-2Unit 3 lecture-2
Unit 3 lecture-2
 
Java Comparable and Comparator
Java Comparable and ComparatorJava Comparable and Comparator
Java Comparable and Comparator
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Number 1 I have completed and number 6 is just uploading I .pdf
Number 1 I have completed and number 6 is just uploading I .pdfNumber 1 I have completed and number 6 is just uploading I .pdf
Number 1 I have completed and number 6 is just uploading I .pdf
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
Algorithms: I
Algorithms: IAlgorithms: I
Algorithms: I
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Comparable Interface1.Comparable is the interface which is present.pdf
Comparable Interface1.Comparable is the interface which is present.pdfComparable Interface1.Comparable is the interface which is present.pdf
Comparable Interface1.Comparable is the interface which is present.pdf
 
Interfaces .ppt
Interfaces .pptInterfaces .ppt
Interfaces .ppt
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.ppt
 
Collections
CollectionsCollections
Collections
 
Kotlin Playground.pptx
Kotlin Playground.pptxKotlin Playground.pptx
Kotlin Playground.pptx
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
 
Overview of Java
Overview of Java Overview of Java
Overview of Java
 
C++Sortable ObjectsStudy the file Sortable.h. It contains a simp.pdf
C++Sortable ObjectsStudy the file Sortable.h. It contains a simp.pdfC++Sortable ObjectsStudy the file Sortable.h. It contains a simp.pdf
C++Sortable ObjectsStudy the file Sortable.h. It contains a simp.pdf
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in Spring
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
PATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and JavaPATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and Java
 

Recently uploaded

Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
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
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
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
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 

Recently uploaded (20)

Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
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
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
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
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 

Comparable vs comparator

  • 1. Comparable Vs Comparator Both are used to sort the objects of the class. Packages: Comparable is in: java.lang Comparator is in: java.util Syntax: Interface Comparable<T> T- the type of object that this object may be compared to Interface Comparator<T> T- the type of object that this object may be compared to Class implementing Comparable interface need to override int compareTO(T o) which compares this obj with specified object for order. Class implementing Comparator interface need to override int compare(T o1, T o2) compares its two arguments for order. boolean equals(Object o) indicates whether some other object is "equal to" this comparator. Comparable When we create list(or array) of object of user defined class, we cannot call Collection.sort() method to sort object in the list, because they do not have natural ordering. To define natural ordering we implement Comparable interface on the Object we want to compare our class to. Implementing class must override compareTo(Object o) method Example: class Employee implements Comparable<Employee> { int id; String name; int compareTo(Employee emp) { return (this.id<emp.id) ? -1 : (this.id>emp.id) ? 1 : 0; } }
  • 2. When -1: this returned that means: this object’s id is less than emp.id When 1: this returned that means: this object’s id is greater than emp.id When 0: both objects are equal. OR return this.id.compareTo(emp.id); This will return result in ascending order. To print in descending order: return –this.id.compareTo(emp.id); // - negative sign returns decending Comparator The class whose objects to be sorted do not need to implement this interface. Some third class can implement this interface to sort. E.g., EmployeeSortByIdComparator class can implement Comparator interface to sort collection of employee object by id. Using Comparator interface, we can write different sorting based on different attributes of objects to be sorted. Parameter Comparable Comparator Sorting Logic Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id,name etc. Implementation Class whose objects to be sorted must implement this interface. e.g. Employee class needs to implement comparable to collection of country object by id Sorting method int compareTo(Object o1) This method compares this object with o1 object and returns a integer. Its value has following meaning positive – this object is greater than o1 zero – this object equals to o1 Class whose objects to be sorted do not need to implement this interface. Some other class can implement this interface. E.g.EmployeeSortByIdComparator class can implement Comparator interface to sort collection of country object by id int compare(Object o1,Object o2) This method compares o1 and o2 objects. and returns a integer.Its value has following meaning. positive – o1 is greater than o2
  • 3. Calling method negative – this object is less than o1 Collections.sort(List) Here objects will be sorted on the basis of CompareTo method zero – o1 equals to o2 negative – o1 is less than o1 Collections.sort(List, Comparator) Here objects will be sorted on the basis of Compare method in Comparator