What is the Comparator interface?
Are you preparing for IT certification? With practice questions, study notes, interactive quizzes, tips and technical articles, uCertify PrepKits ensure that you get a solid grasp of core technical concepts to ace your certification exam in first attempt.
What is the Comparator interface?
Rating:
The Comparator interface is used to sort the elements of collections and arrays. It differs from the Comparable interface in that the Comparable interface sorts the elements only in the natural order. In contrast, the Comparator interface sorts the collections and arrays in a number of different ways.
The Comparator interface has a single compare() method, which returns an integer. It has the following signature:
- negative if Obj1 < Obj2
- positive if Obj1 > Obj2
- zero if Obj1 < Obj2
The Comparator interface can sort only the mutually comparable objects. It cannot be used to sort primitives. Sorting elements using the Comparator interface requires building a class separate from the class whose instances are to be sorted. This is in contrast to the Comparable interface, in which case the class to be sorted itself uses the Comparable interface.
Rating:
Was this information helpful?
Other articles
- What is the List interface?
- What is the parseInt() method?
- What are unary + and - operators?
- What is the instanceof operator?
- What is the NumberFormat class?