Java Comparable example

  1. Comparable interface is present in java.lang package .
  2. Its contains only one method compareTo(Object).It is used to compare the current object with the specified object. 
    Comparable.java
    public interface Comparable<T>
    {
        public int compareTo(T o);
    }
  3. You can sort the elements on the basis of single data member only.
  4. Using Comparable interface, we can sort the elements of:
    • String objects.
    • Wrapper class objects, for example Long, Integer etc.
    • User defined custom objects.
  5. Comparable interface defines a natural ordering of elements.

Example : Sort student object based on student name , if student name is same then sort on basic of  student phone.

class Student implements Comparable<Student>{
    private int student_id;
    private String student_name;
    private String student_phone;
    @Override
    public int compareTo(Student student){
        int flag= this.student_name.compareTo(student.student_name);
        return falg== 0 ? this.student_phone.compareTo(other.student_phone) : flag;
    }
}

Leave a comment