Updated July 24, 2023
Overview of Comparable in Java Example
Comparable in Java is an interference used to compare current objects with other objects of the same type. This comparison can be used to sort elements in a collection. You will have to implement an interface into a class to make it sortable or “comparable.” You will have to implement just one method, “compareTo.” This ordering of any type is called natural ordering, and the implemented “compareTo” method is called the natural comparison method. Here in this Comparable in Java Example article, we will look at the different examples on comparable in java.
Working of Comparable in Java with Example
The working of comparable in java is as follows:
Declaration:
Interface Comparable<T>
To implement this interface, you must implement this method:
public int compareTo(To);
Parameters:
T – is the type of object with which this object is compared to.
Return value:
compareTo method returns 0 if the object specified and this object is equal. It returns a negative integer if this object is less than the object specified. It returns a positive integer if this object is greater than the specified object.
Throws:
- ClasscastException – If the object passed to this method is null
- NullPointerException – If the object passed to this method is not compatible with this object.
Classes that implement Comparable interface have their natural ordering specified with them, and so they can be sorted directly in Collection or Arrays using Collections.sort() and Arrays.sort(). They can also be used as the key in sorted maps and elements in sorted sets without specifying the comparison separately.
Let’s understand the Comparable interface with the help of an example:
Example:
package comparableDemo;
import java.util.TreeSet;
public class Student implements Comparable<Student> {
private int rollNo;
private String name;
private int age;
public Student(int rollNo, String name, int age) {
this.rollNo = rollNo;
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
if (this.rollNo > o.rollNo) {
return 1;
} else if (this.rollNo == o.rollNo) {
return 0;
} else {
return -1;
}
}
@Override
public String toString() {
return "RollNo-" + this.rollNo + ", Name-" + this.name + ", Age-" + this.age;
}
public static void main(String[] args) {
TreeSet<Student> students = new TreeSet<>();
Student student1 = new Student(3, "Raj", 20);
Student student2 = new Student(5, "Shyam", 18);
Student student3 = new Student(1, "Ram", 19);
Student student4 = new Student(4, "Sunil", 25);
Student student5 = new Student(2, "Ajay", 26);
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
students.add(student5);
for (Student student : students) {
System.out.println(student);
}
}
}
Output:
Explanation
This is an application to store student details.
- First, we have created a class “Student” as the representation of the entity Student. Then, we are going to store basic details like roll number, name, and age of students.
- And the requirement is to sort the list of students based on roll number.
- To fulfill this requirement, a Comparable interface is implemented and compared to the students based on roll number, as you can see the implementation of the “compareTo” method.
- Then we have the main method to show the functionality. Here we have created a “TreeSet” and added five students having random roll numbers. We have used “TreeSet” because it stores elements in sorted order.
- Now, if you iterate through the list of students, you will find that students are sorted based on roll number. So that’s what our requirement was!
- We could also sort the students based on other attributes like name or age. To do this, we will have to use name or age variables in the “compareTo” method instead of “rollNo.”
Example:
@Override
public int compareTo(Student o) {
if (this.age> o.age) {
return 1;
} else if (this.age == o.age) {
return 0;
} else {
return -1;
}
}
OR
@Override
public int compareTo(Student o) {
return this.name.compareTo(o.name);
}
Comparable vs Comparator
Comparator is also an interface like Comparable, which is used for comparing two objects of a type. The difference is that Comparator is not implemented in the entity class itself. We must implement it in another class and provide the instance of it to the sorting mechanism explicitly. We can also use an anonymous class instance for this purpose.
For example, suppose we have a Student class without implementing a Comparable interface:
package comparableDemo;
import java.util.TreeSet;
public class Student{
private int rollNo;
private String name;
private int age;
public Student(int rollNo, String name, int age) {
this.rollNo = rollNo;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "RollNo-" + this.rollNo + ", Name-" + this.name + ", Age-" + this.age;
}
public static void main(String[] args) {
TreeSet<Student> students = new TreeSet<>();
Student student1 = new Student(3, "Raj", 20);
Student student2 = new Student(5, "Shyam", 18);
Student student3 = new Student(1, "Ram", 19);
Student student4 = new Student(4, "Sunil", 25);
Student student5 = new Student(2, "Ajay", 26);
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
students.add(student5);
for (Student student : students) {
System.out.println(student);
}
}
}
If you try to execute this program, you will get this exception:
Because TreeSet needs a way to sort the elements.
To resolve this error, we can use Comparator as implemented in this program:
package comparableDemo;
import java.util.Comparator;
import java.util.TreeSet;
public class Student {
private int rollNo;
private String name;
private int age;
public Student(int rollNo, String name, int age) {
this.rollNo = rollNo;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "RollNo-" + this.rollNo + ", Name-" + this.name + ", Age-" + this.age;
}
public static void main(String[] args) {
Comparator<Student> studentComparator = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if (o1.rollNo < o2.rollNo) {
return -1;
} else if (o1.rollNo == o2.rollNo) {
return 0;
} else {
return 1;
}
}
};
TreeSet<Student> students = new TreeSet<>(studentComparator);
Student student1 = new Student(3, "Raj", 20);
Student student2 = new Student(5, "Shyam", 18);
Student student3 = new Student(1, "Ram", 19);
Student student4 = new Student(4, "Sunil", 25);
Student student5 = new Student(2, "Ajay", 26);
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
students.add(student5);
for (Student student : students) {
System.out.println(student);
}
}
}
You can see that the Comparator interface is implemented in an anonymous inner class, and the instance is provided to TreeSet for sorting elements. Now you will get a proper output as earlier.
Collection interface in Java
The collection is the root interface in the collections framework. It contains the declaration of all general-purpose methods which are implemented in collections like Lists and Sets. Map interface does not extend the Collection interface because Map is a collection of key-value pairs and not just a collection of elements. Some of the Collection interface methods are implemented in an abstract class, “AbstractCollection”.
This interface is not directly implemented but extended by specific interfaces because its implementation is collection specific. For example, some collection allows duplicate elements (Ex- List) whereas some do not (Ex- Set), some maintain indexing (Ex- List) whereas some do not (Ex- Set).
Some important methods are described here:
- Boolean add(E e): This method adds an element to this collection and returns the add operation status.
- boolean addAll(Collection<? extends E> c): This method adds all the elements from the specified collection into this collection and returns the add operation status.
- void clear(): This method removes all the elements from this collection.
- boolean contains(Object o): This method checks if the specified element is present in the collection or not. Returns true or false accordingly.
- boolean contains(Collection<?> c): This method checks if all the specified collection elements are present in this collection or not and returns true or false accordingly.
- boolean isEmpty(): This method checks if the collection is empty or not and returns true or false accordingly.
- Iterator<E> iterator(): This method returns an iterator for this collection. Iterator is used to iterate through all the elements in this collection.
- boolean remove(Object o): This method removes the specified element from the collection and returns the remove operation status.
- boolean removeAll(Collection<?> c): This method removes all the elements from this collection that are present in the specified collection and this collection.
- boolean retainAll(Collection<?> c): This method removes all the elements from this collection that are not present in the specified collection and present in this collection.
- int size(): This method returns the size of this collection.
- Object[] toArray(): This is an important method which forms and returns the array containing all the elements of this collection.
- <T> T[] toArray(T[] a): This method adds all the elements of this collection into a specified array and returns the array. If the size of the array is less than the size of this collection, then it creates a new array of types the same as the type of specified array and returns it. If the specified array size is more than the size of this collection, the null value is set for the array’s remaining elements and returns the array.
Conclusion
To summarize, the Comparable in Java interface is very useful for comparing objects manually, sort collections and arrays or having a sorted collection itself. We can also sort elements based on different attributes of the entity. It’s not required but highly recommended to have the same result from equals and the “compareTo” method to avoid the mess in a collection that uses both these methods.
Recommended Articles
This is a guide to Comparable in Java Example. Here we discuss the Introduction Comparable in Java Example, Collection interface in Java, etc. You can also go through our other suggested articles to learn more–