What is the Comparator interface?

August 13th, 2008 by uCertify Leave a reply »

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:

int Obj1.compare(Obj1, Obj2): This method compares the order of the method arguments and returns the following results:

  • negative if Obj1 < Obj2
  • positive if Obj1 > Obj2
  • zero if Obj1 == Obj2

equals(Object obj): This method is used to compare the equality of two objects. The objects being compared must also implement the Comparator interface.

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.

  • Share/Bookmark
Advertisement

Leave a Reply

uCertify.com | Our Company | Articles | Contact Us | News and Press Release | uCertify India | Entries (RSS)
MCSE: MCSA, MCTS, MCITP    JAVA Certification: SCJP, SCWCD    Cisco Certification: CCNA, CCENT    A+, Network+, Security+ Project+
Oracle Certification: OCP 11g, OCP 10g, OCA 11g, OCA 10g    CIW foundation    EC-212-32,    CISSP    Photoshop ACE CS4    Adobe Flash ACE, PMP, CAPM
© 2008 uCertify.com. All rights reserved. All trademarks are the property of their respective owners.