2

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.

Timuçin
  • 4,653
  • 3
  • 25
  • 34
user998692
  • 5,172
  • 7
  • 40
  • 63

2 Answers2

2

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.

Mik378
  • 21,881
  • 15
  • 82
  • 180
1

The question is valid and the right answer is "D) Compilation fails".

If you check the page page with the questions you can find the answers at the bottom of it, and for this question is marked D

Eduardo
  • 27
  • 3