Introduction
Comparable interface in Java
- User-defined class object
- String object
- Wrapper class object
String and wrapper classes implement the comparable interface. So, if you store the objects of the wrapper or string classes, then it will be comparable.
Some syntax that is used in the Comparable interface:
- Collection.sort(): It is used to sort the collection of a class's objects.
- Array.sort(): It is used to sort the elements of a class's objects.
- Compare.To(): It is used to compare the current object with a specified object.
- Void.sort(): It is used to sort the elements of a list. The list should be of comparable type.
The following are examples of sorting a collection of Java objects, using the comparable interface.
Employee.java
- class Employee implements Comparable {
- int id;
- String name;
- int age;
- String address;
- int salary;
- Employee(int id, String name, int age, String address, int salary) {
- this.id = id;
- this.name = name;
- this.age = age;
- this.address = address;
- this.salary = salary;
- }
- public int compareTo(Object obj) {
- Employee E = (Employee) obj;
- if (age == E.age)
- return 0;
- else if (age > E.age)
- return 1;
- else
- return -1;
- }
- }
- Main.java
- import java.util.*;
- class Main {
- public static void main(String args[]) {
- ArrayList EL = new ArrayList();
- EL.add(new Employee(1001, "Shubham", 19, "Jhansi", 5000));
- EL.add(new Employee(1002, "Akash", 23, "Lucknow", 10000));
- EL.add(new Employee(1003, "Ravi", 34, "Kanpur", 12000));
- EL.add(new Employee(1004, "Shashikant", 21, "Delhi", 15000));
- Collections.sort(EL);
- Iterator itr = EL.iterator();
- while (itr.hasNext()) {
- Employee s = (Employee) itr.next();
- System.out.println(s.id + " " + s.name + " " + s.age + " " + s.address + " " + s.salary);
- }
- }
In the preceding example, we sorted the employee list based on their age, the output is as follows:
Output
If we sort the employee list based on their salary, the output will be as follows:
Output
And, if we sort the employee list based on their id, then the output will be as follows:
Output
You can also sort the list depending on their name or address.




Join the conversation! Your thoughts help the community grow.