In this article, we are going to discuss the Comparable interface in java and the Comparator interface with an example, and their methods.
Comparable interface
Comparable Interface present in java.lang Package. It is mainly used to sort the arrays or lists of custom objects. It contains only one method compareTo().
Syntex:
public int compareTo(Object obj);
Simple example:
obj1.compareTo(Object obj2)
- Its returns a positive integer (-ve) value, if and only if obj1 has to come before obj2.
- Its returns a negative integer (+ve) value if and only if obj1 has to come After obj2
- It returns zero(0) value if and only if obj1 and obj2 are equal.
Example:
package com.technicalround; import java.util.*; class compareToDemo { public static void main(String[] args) { System.out.println("A".compareTo("Z")); // -25 System.out.println("Z".compareTo("K")); // 15 System.out.println("Z".compareTo("Z")); // 0 System.out.println("Z".compareTo(null)); // RE: java.lang.NullPointerException } }
Output:
-25 15 0 RE: java.lang.NullPointerException
If we depend on default natural sorting order and if we are trying to insert elements then internally JVM will Call compareTo() method to identify sorting order.
When we are inserting an object in trees, then internally JVM will Call compareTo() method, and then they compare the object.
Example:
package com.technicalround; import java.util.*; class Demo { public static void main(String[] args) { TreeSet ts = new TreeSet(); ts.add("K"); ts.add("Z"); // +ve "Z".compareTo("K") ts.add("A"); // -ve "A".compareTo("K") ts.add("A"); // 0 "A".compareTo("A") System.out.println(ts); } }
Output:
[A, K, Z]
When we are not satisfied with the default natural sorting order or if the default natural sorting order is already not available then we can define our own sorting by using Comparator Object.
Comparable meant for default natural sorting order whereas Comparator meant for customized sorting order.
Comparator interface
We can use Comparator to define our own sorting (customized sorting) order. Comparator Interface present in java.util Package.
Comparator Methods: It contains 2 Methods.
- compare() method
- equals() method.
compare() method:
public int compare(Object obj1, Object obj2);
- It returns a positive integer (-ve) if and Only if obj1 has to Come Before obj2.
- It returns a negative integer (+ve) if and Only if obj1 has to Come After obj2.
- Returns zero(0) if and only if obj1 and obj2 are equal.
equals() method:
It is returning a boolean value (true/false). we are checking object is equal or not using the equals() method.
Whenever we are implementing Comparator Interface compulsory we should provide an implementation for compare() method. When we are implementing the equals() method is optional because it is already available to our Class from object Class through Inheritance.
Example:
package com.technicalround; import java.util.*; class Demo { public static void main(String[] args) { TreeSet ts = new TreeSet(new MyComparator()); ts.add(10); ts.add(0); // compare(0,10);+1 ts.add(15); // compare(15,10);-1 ts.add(5); // compare(5,15); +ve ,compare(5,10); +1, compare(5,0); -1 ts.add(20); // compare(20,15); -1 ts.add(20); // compare(20,20); 0 System.out.println(ts);// [20, 15, 10, 5, 0] } } //Creating our own Customized Sorting class MyComparator implements Comparator { public int compare(Object obj1, Object obj2) { Integer i1 = (Integer) obj1; Integer i2 = (Integer) obj2; if (i1 < i2) return +1; else if (i1 > i2) return -1; else return 0; } }
Output:
[20, 15, 10, 5, 0]
In above example when we are not passing Comparator Object as an argument in (TreeSet ts = new TreeSet();) Internally JVM will Call compareTo(). which is providing default natural sorting order (Ascending Order) then output is like [0, 5, 10, 15, 20].
when we are passing Comparator Object as an argumen in (TreeSet ts = new TreeSet(new MyComparator());) then JVM will Call compare() Instead of ompareTo(). Then we are getting Customized Sorting (Descending Order), then output is [20, 15, 10, 5, 0].
Example:
class Demo { public static void main(String[] args) { TreeSet ts = new TreeSet(new MyComparator()); ts.add("Niraj"); ts.add("Rahul"); ts.add("Kunal"); ts.add("Amit"); ts.add("Sunil"); System.out.println(ts); } } class MyComparator implements Comparator { public int compare(Object obj1, Object obj2) { String s1 = obj1.toString(); String s2 = (String) obj2; return s2.compareTo(s1);// [Sunil, Rahul, Niraj, Kunal, Amit] // return -s1.compareTo(s2);//valid } }
Output:
[Sunil, Rahul, Niraj, Kunal, Amit]
In the above program, we are insert string objects into the TreeSet where the sorting order is of the reverse of alphabetical order.
In which case we need to use Comparable.
- For predefined comparable classes (Like String) default, natural sorting order is already available.
- For predefine Non-Comparable classes (Like StringBuffer) default, natural sorting order is not already available.
In which case we need to use Comparator.
- If we are not satisfied with that we can Define Our Own Sorting by Comparator Object.
- If we want to Define Our Own Sorting we can Use Comparator Object.
Difference between Comparable and Comparator:
- Comparable present in java.lang package where Comparator presents in java.util package.
- Comparable is meant for default natural sorting where Comparator is meant for customized sorting order.
- All wrapper classes and string class implements Comparable Interface where Comparator implements are Collator and RuleBaseCollator.
- Comparable fefines only one method compareTo() where Comparator defines two methods compare() and equals().
Read More topics related to the collection.
Read more topics related to java
- Multithreading in java
- Inter thread communication in java
- synchronization in java
- Exception in java
- Inner class in java
Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.