nerdexam
Oracle

1Z0-819 · Question #70

public class Tester { public static class Person implements / line 1 / { private String name; Person(String name) { this.name = name; } / line 2 / } public static void main(String[] args) { Person[]…

The correct answer is B. Insert Comparator<Person> on line 1. Insert public int compareTo(Person person) { return person.name.compare(this.name); } on line 2. See the full explanation below for the reasoning.

Question

public class Tester { public static class Person implements /* line 1 / { private String name; Person(String name) { this.name = name; } / line 2 */ } public static void main(String[] args) { Person[] people = new Person("Mary"), new Person("Jane"); new Person("John"); Arrays.sort(people); for (Person person: people) System.out.println(person.name); } } You want the code to produce this output: Jane John Mary Which code fragment should be inserted on line 1 and line 2 to produce the output?

Options

  • AInsert Comparator<Person> on line 1. Insert public int compare(Person p1, Person p2) { return p1.name.compare(p2.name); } on line 2.
  • BInsert Comparator<Person> on line 1. Insert public int compareTo(Person person) { return person.name.compare(this.name); } on line 2.
  • CInsert Comparable<Person> on line 1. Insert public int compare(Person p1, Person p2) { return p1.name.compare(p2.name); } on line 2.
  • DInsert Comparator<Person> on line 1. Insert public int compare(Person person) { return person.name.compare(this.name); } on line 2.

How the community answered

(44 responses)
  • A
    5% (2)
  • B
    80% (35)
  • C
    2% (1)
  • D
    14% (6)

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice