Wednesday, April 24, 2019

Comparable Vs Comparator In Java

Q- What is comparable in Java?

Q- What is comparator in Java?

Q- How do you compare objects in Java?

Q- What is the difference between comparator and comparable in java ?

Q- Which is better comparator or comparable in Java?

Q- When to use  Comparable  or Comparator in Java? 

  Comparable interface is defined in java.lang package Comparator is defined in java.util package
  It has public int compareTo(Object o) method.
  We have to provide implementation (override) of                                     compareTo(Object o)  in such a way that should  return -1,0,1,
  while "this" object is less than, equal to, or greater than the object       which we have to pass as argument.
   It has  public int compare (Object o1, Object o2) method .
   We have to provide implementation of  compare (Object o1, Object        o2)  in such a way that should  rerurn -1,0,1
   while  first object is less than, equal to, or greater than the second             object .
  Comparable is used to implement natural ordering of object. All the    java API and wrapper class implements Comparable interface by      defaults.  This is used to sort in non-natural order,
  it means to sort on complex order.
  Any class which implements Comparable. its object can used as          keys  in a SortedMap like TreeMap without specifying any                    Comparator.

  only one logic of sorting by implements Comparable, it means only       can sorting on any one property.  Object can be sorted on multiple properties
   like id, name, email address etc.
  implements Comparable interface is required in a class to override      compareTo(Object o) method.  Implements Comparator interface in a class is optional.
  Because we can create separate comparator class to override compare    (Object o1, Object o2) method .
  Source class is required.

Use : Collections.sort(list) method to sort
  Source class not required its optional for this
  Use : Collections.sort(list, comparator) method to sort 

No comments:

Post a Comment