Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 31
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.Arrays;
- import java.util.Comparator;
- import java.util.List;
- class Student implements Comparator<Student> {
- private String name;
- private String exam;
- public Student() {
- super();
- }
- public Student(String name, String exam) {
- this.name = name;
- this.exam = exam;
- }
- public int compare(Student s1, Student s2) {
- return s2.name.compareToIgnoreCase(s1.name);
- }
- public String toString() {
- return '{' + name + ", " + exam + '}';
- }
- }
- public class Test {
- public static void main(String[] args) {
- Student stud1 = new Student("John", "OCA");
- Student stud2 = new Student("Jack", "OCP");
- Student stud3 = new Student("Rob", "OCP");
- List<Student> list = Arrays.asList(stud1, stud2, stud3);
- list.sort(new Student());
- list.forEach(System.out::println);
- }
- }
What will be the result of compiling and executing Test class?
- A Compilation error
-
B
{Rob, OCP}
{John, OCA}
{Jack, OCP} - C Runtime exception
-
D
{Jack, OCP}
{John, OCA}
{Rob, OCP}
Reveal correct answer
Correct answer: B
Explanation
In real world programming you will hardly find a bean class implementing Comparator but it is a legal code. A bean class generally implements Comparable interface to define natural ordering.
Student class in this case correctly implements Comparator<Student> interface by overriding compare(Student, Student) method.
Note, this compare method will sort in descending order of Student's name.
list.sort(...) accepts an argument of Comparator<Student> type.
new Student() provides the instance of Comparator<Student> type. It sorts list in descending order of Students' name.
Output is:
{Rob, OCP}
{John, OCA}
{Jack, OCP}
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
