Java OCA OCP Practice Question 1356

Question

When should objects stored in a Set implement the java.util.Comparable interface?

  • A. Always
  • B. When the Set is generic
  • C. When the Set is a HashSet
  • D. When the Set is a TreeSet
  • E. Never


D.

Note

TreeSet stores its elements in natural order, which is determined by casting the elements to Comparable and invoking their compareTo() methods. If you add an element that isn't comparable to a tree set, you'll eventually get an exception.




PreviousNext

Related