by @kodeazy
what is comparable in java and how it works?
- comparable is an interface used to sort objects of user defined class.
- It is found in
java.lang
package. public void sort(List list)
method of collection interface is used to sort the objects.- For Example
Collections.sort(al);
hereal
is an object. -
compareTo(Object)
method Compares current object with the specified object for order to sort in ascending or descending order as per the requirment.public int compareTo(Employee e){ if(salary>e.salary) return 1; else if(salary<e.salary) return -1; else return 0; }
compareTo(Object)
method returnspositive
ornegitive
orzero
as above.- Above method returns
Objects
inAsc
order -
To print in
Desc
order just modify the method return statments from1 to-1
and-1 to 1
as below incompareTo(Object)
methodpublic int compareTo(Employee e){ if(salary>e.salary) return -1; else if(salary<e.salary) return 1; else return 0; }
Below is the Example to Sort and display employees data based on their salary in Ascending Order
import java.util.*; class Employee implements Comparable<Employee>{ int age; int salary; String name; Employee(int age,int salary,String name){ this.age=age; this.salary=salary; this.name=name; } public int compareTo(Employee e){ if(salary>e.salary) return 1; else if(salary<e.salary) return -1; else return 0; } } class ComparableExample{ public static void main(String args[]){ List<Employee> al=new ArrayList<Employee>(); al.add(new Employee(27, 103, "Suresh")); al.add(new Employee(23, 102, "Ramesh")); al.add(new Employee(21, 105, "Mahesh")); al.add(new Employee(29, 104, "Gopi")); Collections.sort(al); Iterator<Employee> it=al.iterator(); System.out.println("Details after sorting"); while(it.hasNext()){ Employee e=(Employee)it.next(); System.out.println("Name :"+e.name+" salary :"+e.salary+" Age :"+e.age); } } }
Output:
Name :Ramesh salary :102 Age :23 Name :Suresh salary :103 Age :27 Name :Gopi salary :104 Age :29 Name :Mahesh salary :105 Age :21