Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 67
Question ID: UKOCP88283
What will be the result of compiling and executing Test class?
- package com.udayankhattry.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 compare(Point o1, Point o2) {
- return o2.getX() - o1.getX();
- }
- });
- System.out.println(points);
- }
- }
- A [Point(2, 2), Point(4, 5), Point(6, 7)]
- B [Point(6, 7), Point(4, 5), Point(2, 2)]
- C [Point(4, 5), Point(6, 7), Point(2, 2)]
- D Compilation error
Reveal correct answer
Correct answer: B
Explanation
UKOCP88283:
return o2.getX() - o1.getX(); means the Comparator is sorting the Point objects on descending value of x of Point objects.
To sort the Point objects in ascending order of x, use: return o1.getX() - o2.getX();
To sort the Point objects in ascending order of y, use: return o1.getY() - o2.getY();
To sort the Point objects in descending order of y, use: return o2.getY() - o1.getY();
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.
