Which code fragment should be inserted on line 1 and line 2 to produce the output?

Given:

You want the code to produce this output:
John Joe
Jane
Which code fragment should be inserted on line 1 and line 2 to produce the output?
A. Insert Comparator<Person> on line 1.
Insert
public int compare(Person p1, Person p2) { return p1.name.compare(p2.name);
} on line 2.
B. Insert Comparator<Person> on line 1.
Insert
public int compareTo(Person person) { return person.name.compareTo(this.name);
} on line 2.
C. Insert Comparable<Person> on line 1.
Insert
public int compare(Person p1, Person p2) { return p1.name.compare(p2.name);
} on line 2.
D. Insert Comparator<Person> on line 1.
Insert
public int compare(Person person) { return person.name.compare(this.name);
} on line 2.

Download Printable PDF. VALID exam to help you PASS.

3 thoughts on “Which code fragment should be inserted on line 1 and line 2 to produce the output?

  1. The other interesting fact is the following one: according to the Arrays.sort(Object[] a); JavaDoc it is expected that all the elements within the array implements Comparable interface.

    “Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).
    This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.”

  2. public class Tester {

    static class Person implements Comparable {
    private String name;

    public String getName() {
    return name;
    }

    public Person(String name) {
    this.name = name;
    }

    @Override
    public int compareTo(Person o) {
    return o.getName().compareTo(this.name);
    }
    }

    public static void main(String[] args) {
    Person[] people = {new Person(“Joe”), new Person(“Jane”), new Person(“John”)};

    Arrays.sort(people);

    for (Person person : people) {
    System.out.println(person.getName());
    }
    }

    John
    Joe
    Jane

    8
    1
  3. all of them are wrong:
    Comparator defines compare(p1, p2) method, then B and D are wrong.
    Comparable defines compareTo(p) method, then C is wrong.

    and A option doesnt work because String doesnt implement compare(String, String)

    16

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.