Monday, 1 August 2016

Java Comparable interface

Java Comparable interface is used is used to impose a natural ordering sorting. This interface is found in java.lang package and contains only one method named compareTo(Object).

It provides single sorting sequence i.e. in comparable, only one sort sequence can be created. We need to modify the class whose instances we want to sort.

Lists and Arrays of objects that implement comparable interface can be sorted automatically by Collections.sort() (and Arrays.sort()).

Objects which implement Comparable in Java can be used as keys in a SortedMap like TreeMap or elements in a SortedSet for example TreeSet.

import java.util.*;

class Employee implements Comparable<Employee> {
       int id;
       String name;

       public Employee(int id, String name) {
              this.id =  id;
              this.name =  name;
       }

       //@Override
       public int compareTo(Employee object) {
              if(object==null ||this.getName()==null||object.getName()==null) {
                     return 0;
              }
              return this.getName().compareTo(object.getName());
       }

       public int getId() {
              return id;
       }

       public void setId(int id) {
              this.id = id;
       }

       public String getName() {
              return name;
       }

       public void setName(String name) {
              this.name = name;
       }

}

public class ComparableTest {

       public static void main(String[] args) {
              Employee emp1 = new Employee(1, "Vishal");
              Employee emp2 = new Employee(4, "Deshraj");
              Employee emp3 = new Employee(3, "Ashish");
              Employee emp4 = new Employee(2, "Yatin");

              List<Employee> list = new ArrayList<Employee>();
              list.add(emp1); list.add(emp2);
              list.add(emp3); list.add(emp4);
             
              System.out.println("Before sort: ");
              printListUtil(list);
             
              Collections.sort(list);
              System.out.println("After sort: ");
              printListUtil(list);
       }

       private static void printListUtil(List<Employee> list) {
              for(Employee emp : list) {
                     System.out.println("ID# "+ emp.getId() + ", Name: "+ emp.getName());
              }
       }
}

Output:
Before sort:
ID# 1, Name: Vishal
ID# 4, Name: Deshraj
ID# 3, Name: Ashish
ID# 2, Name: Yatin
After sort:
ID# 3, Name: Ashish
ID# 4, Name: Deshraj
ID# 1, Name: Vishal
ID# 2, Name: Yatin

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...