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;
}
}
0 Comment(s)