KEMBAR78
Comparable Vs Comparator Interface | PDF
0% found this document useful (0 votes)
27 views1 page

Comparable Vs Comparator Interface

Uploaded by

sharmilapv84
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views1 page

Comparable Vs Comparator Interface

Uploaded by

sharmilapv84
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Comparable Vs Comparator Interface

Comparable
 The Comparable interface provides a single sorting sequence. For example: Consider a Movie class
that has members like, rating, name, year. Suppose we wish to sort a list of Movies based on year of
release. We can implement the Comparable interface with the Movie class, and we override the
method compareTo() of Comparable interface.
 It contains a single method compareTo(Object obj) which compares the object with another object.
 By implementing Comparable, a class indicates that its instances can be sorted using the natural
ordering.
 For example, classes like String, Integer, and Date implement Comparable to define their natural
ordering.

Comparator
 The Comparator interface provides multiple sorting sequences. For example, Now, suppose we want
to sort movies by their rating and names as well. When we make a collection element
comparable(by having it implement Comparable), we get only one chance to implement the
compareTo() method. The solution is using Comparator.
 The Comparator interface provides a way to define custom ordering for objects that may not have a
natural ordering or for cases where you want to define multiple sorting criteria.
 It contains two methods:
o The compare(Object obj1, Object obj2) method compares two objects for ordering.
o The equals(Object obj) method checks whether the Comparator is equal to another Comparator.

Comparable Comparator
The Comparable interface provides a single sorting The Comparator interface provides multiple
sequence. sorting sequences.
compareTo() method is used to sort elements. compare() method is used to sort elements.
Comparable is present in the package java.lang Comparator is present in the package java.util

We can sort the list elements of Comparable type We can sort the list elements of Comparator type
by Collections.sort(List) method. by Collections.sort(List, Comparator) method.

You might also like