Smart Programming : Channel
An investment in Knowledge pays the best interest….
Comparable & Comparator
in Java
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
=> Comparable :
Comparable is an interface which is present in
java.lang package
It contains only one method i.e. compareTo()
o Prototype : public int compareTo(Object obj)
obj1.compareTo(obj2);
+ve - if obj1 is greater than obj2
-ve - if obj2 is greater than obj1
0 - if obj1 is equals to obj2
String and all wrapper classes (Integer, Long,
Float etc) implements Comparable interface
Problems with Comparable interface :-
1. By implementing Comparable interface, the
properties of Original class will get changed
2. By this way we can sort only for one entity for
example we can sort the student object either
with name or rollno at one time
(To remove above problems java provided one
interface i.e. Comparator)
1
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
=> Comparator :-
-> Comparator is an interface which is present in
java.util package
-> Comparator interface contains 2 methods :-
1. public int compare(Object obj1, Object obj2)
2. public boolean equals(Object obj)
=> TASK : WAP to compare and add different
elements according to length and alphabetical order
For example :
A, B, AA, BB, AAA, BBB, AAAA
2
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
=> What is difference between Comparable &
Comparator interface :-
1. Comparable interface contains compareTo()
method
Comparator interface contains compare() method
2. Comparable interface is present in java.lang
package
Comparator interface is present in java.util
package
3. By using Comparable interface original class
properties will get changed
By using Comparator interface original class
properties will not be changed
3
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
4. Comparable interface can sort only one entity
Comparator interface can sort multiple entities
5. Comparable interface is used to implicit sorting
Comparator interface is used for explicit sorting
4
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
Company Links & Contacts
Company Name: Smart Programming (+91 62838-30308)
Address : Chandigarh & Mohali (Punjab), India
Websites: https://www.smartprogramming.in/
https://courses.smartprogramming.in
Android App:
https://play.google.com/store/apps/details?id=com.sma
rtprogramming
YouTube Channel:
https://www.youtube.com/c/SmartProgramming