Java OCA OCP Practice Question 2794

Question

Given the proper import(s), and given:

class NameCompare implements Comparator<Shape> {
   public int compare(Shape a, Shape b) {
      return b.name.compareTo(a.name);
   }/*from   w  w  w. j  av a 2s  .co  m*/
}

class ValueCompare implements Comparator<Shape> {
   public int compare(Shape a, Shape b) {
      return (a.value - b.value);
   }
}

Which are true? (Choose all that apply.)

  • A. This code does not compile.
  • B. This code allows you to use instances of Shape as keys in Maps.
  • C. These two classes properly implement the Comparator interface.
  • D. NameCompare allows you to sort a collection of Shape instances alphabetically.
  • E. ValueCompare allows you to sort a collection of Shape instances in ascending numeric order.
  • F. If you changed both occurrences of "compare()" to "compareTo()", the code would compile.


C and E are correct.

Note

The code is legal and Collections.sort() can use the ValueCompare.compare() method to sort in ascending numeric order.

A is incorrect based on the above.

B is incorrect because this code doesn't show us whether Shape has overridden equals() and hashCode(), which would allow Shape to be used successfully for keys.

D is incorrect because the NameCompare.compare() method would be used to create sorts in reverse-alphabetical order.

F is incorrect based on the above.




PreviousNext

Related