0
Sponsored Links


Ad by Google
Yes, very popular java interview question specially for 2 to 5 years of experienced candidates, So today we will share you the key differences between Comparator and Comparable interface. In our previous post we have posted a tutorial on java.util.Comparator and java.lang.Comparable

Well, If you want to sort a Collection of objects of similar types, than what you need to do is, you have to do a comparison between objects in order to sort an elements of Collection. And off course Sorting can be of two types Natural Sorting and User defined Sorting. Natural sorting like Numerical order Alphabetical or Chronological order and User defined like, sorting based order date, sorting based on employee age, etc.

We have listed few key differences between Comparator and Comparable interface in java.
  1. Comparable interface is in java.lang package whereas Comparator interface is in java.util package.
  2. java.lang.Comparable interface has only one method public int compareTo(Object obj) whereas java.util.Comparator interface has two methods, public int compare(Object obj1, Object obj2) and public boolean equals(Object obj).
  3. java.lang.Comparable interface can implemented in the same class whose object needs to be sorted whereas java.util.Comparator can be implemented in any class it's not required to implement in the same class such as Comparable. So you can implement any numbers of Comparator interface based on your sorting property.
  4. java.lang.Comparable interface will help you to compare current object with the help of this keyword whereas java.util.Comparator interface will compare two different object.
Syntax of java.lang.Comparable interface:
@Override
 public int compareTo(Contact o) {
  return this.emailID.compareTo(o.getEmailID());
 }
Syntax of java.util.Comparator interface:
@Override
 public int compare(Order obj1, Order obj2) {
  int result = obj1.getEmailId().compareTo(obj2.getEmailId());
  if (obj2.getOrderDate().after(obj1.getOrderDate())) {
   result = -1;
  } else if (obj2.getOrderDate().before(obj1.getOrderDate())) {
   result = 1;
  }
  return result;
 }

References:
Reference 1
Reference 2
Sponsored Links

0 comments:

Post a Comment