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

Discussion

Which of these statements about what Collections.sort requires of the elements it is given is correct?

  • A.The elements must implement Comparable; a Comparator cannot be used with a List.
  • B.The elements must override equals and hashCode consistently.
  • C.The elements must implement Cloneable, since sorting copies the list.
  • D.Either the elements implement Comparable, or a Comparator is supplied.

Answer: D

Correct answer: Either the elements implement Comparable, or a Comparator is supplied.

Collections.sort is overloaded: the one-argument form requires the elements’ natural ordering and throws ClassCastException if they do not implement Comparable, while the two-argument form takes a Comparator and imposes no requirement on the elements at all. Sorting neither copies the list nor consults equals, so Cloneable and the equals contract are irrelevant here.

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

Post your comment

Please log in or register to post a comment.