Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Comparable Interface in Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 491
    Comment on it

    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.


    class Employee implements Comparable{  
    int empId;  
    String name;  
    Employee(int empId,String name){  
    public int compareTo(Object obj){  
    Employee emp=(Employee)obj;  
    return 0;  
    else if(empId>emp.empId)  
    return 1;  
    return -1;  


    import java.util.*;  
    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"));  
    Iterator itr=al.iterator();  
    Employee emp=(Employee);  
    System.out.println(emp.empId+" ";  

    In the above example we sort the list of employee on the basis of their empId.

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: