Java OCA OCP Practice Question 2825

Question

Given:

import java.util.Arrays;
import java.util.Comparator;

public class Main implements Comparator<Main> {
   int dishSize;/*w  w w .ja v a2s . c om*/

   public static void main(String[] args) {
      Main[] va = { new Main(40), new Main(200), new Main(60) };

      for (Main v : va)
         System.out.print(v.dishSize + " ");
      int index = Arrays.binarySearch(va, new Main(60), va[0]);
      System.out.print(index + " ");
      Arrays.sort(va);
      for (Main v : va)
         System.out.print(v.dishSize + " ");
      index = Arrays.binarySearch(va, new Main(60), va[0]);
      System.out.println(index);
   }

   public int compare(Main a, Main b) {
      return a.dishSize - b.dishSize;
   }

   Main(int d) {
      dishSize = d;
   }
}

Which result is most likely?

  • A. Compilation fails.
  • B. "40 200 60 2 40 60 200 1"
  • C. "40 200 60 -2 40 60 200 1"
  • D. "40 200 60", followed by an exception.
  • E. "40 200 60 -2", followed by an exception.


E is correct.

Note

Arrays.sort() assumes that the elements of the array to be sorted implement Comparable unless you provide a Comparator.

Note that Arrays.binarySearch() doesn't throw an exception when passed an unsorted array, it just returns an unpredictable (usually negative) result.




PreviousNext

Related