Machine-translated by Google. Questions are authored in English.
Top

Discussion

Consider what Comparable and Comparator are each for. Which statement is correct?

  • A.Comparable orders objects while a Comparator only tests them for equality.
  • B.Comparable defines a class's own natural ordering; a Comparator is a separate ordering.
  • C.Comparable defines a separate ordering; a Comparator defines the class's natural ordering.
  • D.Both define a natural ordering, but only Comparator may be used by a TreeSet.

Answer: B

A class implements Comparable to declare how its own instances sort, giving one ordering. A Comparator is an external object, so a type can have as many as you need, and it can order a class you did not write or cannot change. Where both are available the comparator wins.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.