Java Comparable interface

Java Comparable interface

Java Comparable interface is used to order the objects of user-defined class.This interface is found in java.lang package and contains only one method named compareTo(Object). It provide single sorting sequence only i.e. you can sort the elements on based on single data member only. For example it may be rollno, name, age or anything else.

compareTo(Object obj) method

public int compareTo(Object obj): is used to compare the current object with the specified object.

 

Comparable Interface Example : -

package codding.time.comparable;
public class Employee implements Comparable<Employee> {
    int empId;
    String name;
    int age;
    Employee(int empId, String name, int age) {
        this.empId = empId;
        this.name = name;
        this.age = age;
    }
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public int compareTo(Employee emp) {
        if (empId == emp.getEmpId()) {
            return 0;
        } else if (empId > emp.getEmpId()) {
            return 1;
        } else {
            return -1;
        }
    }
}

 


package codding.time.comparable;
import java.util.ArrayList;
import java.util.Collections;
public class EmployeeListSortByComparable {
    public static void main(String args[]) {
        ArrayList<Employee> al = new ArrayList<Employee>();
        al.add(new Employee(3, "Raj", 23));
        al.add(new Employee(1, "Tom", 12));
        al.add(new Employee(4, "Ram", 26));
        Collections.sort(al);
        for (Employee emp : al) {
            System.out.println(emp.getEmpId() + " " + emp.getName() + " " + emp.getAge());
        }
    }
}

Output: 

1 Raj 23
3 Tom 12
4 Ram 23

 


 

Related Articles

post a comment