Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Core%20Java%20Interview%20Questions%20and%20Answers

Question: How to use Comparator and Comparable in Java? With example.
Answer: Comparators and comparable in Java are two of fundamental interface of Java API which is very important to understand to implement sorting in Java. It’s often required to sort objects stored in any collection class or in Array and that time we need to use compare () and compare To () method defined in java.util.Comparator and java.lang.Comparable class. Let’s see some important points about both Comparable and Comparator in Java before moving ahead
Difference between Comparator and Comparable in Java
1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package.

2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.

4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.

5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.

6)Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.

Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook