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 packageand 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 implementsComparable<Employee> {
       int id;
       String name;

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

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

       public intgetId() {
              return id;
       }

       public voidsetId(int id) {
              this.id = id;
       }

       public String getName() {
              return name;
       }

       public voidsetName(String name) {
              this.name = name;
       }

}

public class ComparableTest {

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

              List<Employee> list = newArrayList<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...