Search code examples
javajava-7comparatorocpjp

Comparator issue in ocpjp sample questions


I am currently preparing for Java SE 7 Programmer exam and I tried to solve the sample questions on the Oracle site. I got stuck at this one:

import java.util.*;
    public class Primes2 {
        public static void main(String[] args) {
            Integer[] primes = {2, 7, 5, 3};
            MySort ms = new MySort();
            Arrays.sort(primes, ms);
            for(Integer p2: primes)
                System.out.print(p2 + " ");
        }
     static class MySort implements Comparator {
         public int compare(Integer x, Integer y) {
             return y.compareTo(x);
         }
     }
}

What is the result?

A) 2 3 5 7

B) 2 7 5 3

C) 7 5 3 2

D) Compilation fails.

E) An exception is thrown at run time.

The question can be found here: http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=303&p_certName=SQ1Z0_804

The correct answer indicated on the site is C. I tested the code and found it did not compile, because Comparator is parameterized and in the given code the type was not indicated, therefore the compiler expected Object parameters for compare method. When I changed Comparator with Comparator<Integer>, the error was solved and it worked as expected.

My question is whether that declaration in the original code respects the standards of Java 7 and should compile.


Solution

  • Effectively, that does not compile.

    In order to be valid, either Comparator must be typed as Comparator<Integer> or compare() methods arguments must be of Object Type.

    Thus, this exam question is invalid.