Comparable:- Comparable interface found in java.lang package and it contains only compareTo() method. It use the single sorting technique to write our own comparison logic and is used to sort the elements on the basis of single parameter or single datamember of a class like rollno, name, age etc.
Example:-
Employee.java
class Employee implements Comparable{
int empId;
String name;
Employee(int empId,String name){
this.empId=empId;
this.name=name;
}
public int compareTo(Object obj){
Employee emp=(Employee)obj;
if(empId==emp.empId)
return 0;
else if(empId>emp.empId)
return 1;
else
return -1;
}
}
Main.java
import java.util.*;
import java.io.*;
class Main{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Employee(101,"Manish"));
al.add(new Employee(106,"Akki"));
al.add(new Employee(105,"Pratibha"));
Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
Employee emp=(Employee)itr.next();
System.out.println(emp.empId+" "+emp.name);
}
}
}
In the above example we sort the list of employee on the basis of their empId.
0 Comment(s)