top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is difference between Comparable and Comparator interface in Java?

0 votes
442 views
What is difference between Comparable and Comparator interface in Java?
posted Mar 14, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Comparable Interface
Comparable is an public interfaces which is used to impose an natural ordering (if numbers then 1,2,3 or in alphabetical order 'a','b','c' ) of the class that implements it.
Now here the total ordering defines as the natural ordering which means in JVM that when we compare two objects using the comparable interfaces they are actually compared through their ASCII values which is the natural ordering. This means that the comparable by default uses the sorting technique of JVM i.e. Of sorting by the ASCII values.Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort).

Comparator Interface
A comparison function, which is used to impose ordering on some collection of objects. To allow precisely control over the sort order , Comparators can be passed to a sort method (e.g Collections.sort()). Certain type of data structures such as TreeSet or TreeMap can also be sorted using Comparator.

answer Mar 16, 2016 by Shubham Singh
...