Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 18
What will be the result of compiling and executing Test class?
- package com.udayan.ocp;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- class Point {
- private int x;
- private int y;
- public Point(int x, int y) {
- this.x = x;
- this.y = y;
- }
- public int getX() {
- return x;
- }
- public int getY() {
- return y;
- }
- @Override
- public String toString() {
- return "Point(" + x + ", " + y + ")";
- }
- }
- public class Test {
- public static void main(String [] args) {
- List<Point> points = new ArrayList<>();
- points.add(new Point(4, 5));
- points.add(new Point(6, 7));
- points.add(new Point(2, 2));
- Collections.sort(points, new Comparator<Point>() {
- public int compareTo(Point o1, Point o2) {
- return o1.getX() - o2.getX();
- }
- });
- System.out.println(points);
- }
- }
- A Compilation error
- B [Point(4, 5), Point(6, 7), Point(2, 2)]
- C [Point(6, 7), Point(4, 5), Point(2, 2)]
- D [Point(2, 2), Point(4, 5), Point(6, 7)]
Reveal correct answer
Correct answer: A
Explanation
Comparator interface has compare(...) method and not compareTo(...) method.
Anonymous inner class's syntax doesn't implement compare(...) method and thus compilation error.
Make sure to check the accessibility and interface method details before working with the logic.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
