X1042: Complete CompareLastNames

Use the Person class below. Note that this class does NOT implement the Comparable interface.

9
 
1
  public class Person {
2
    // ...
3
    public Person (String f, String l) { ... }
4
    public int compareTo(Person o) { ... }
5
    public String getFirst() { ... }
6
    public String getLast() { ... }
7
    @Override
8
    public String toString() { return getLast()+", "+getFirst(); }
9
  }

For this problem you must complete the following class.

6
 
1
public class CompareLastNames implements Comparator<Person>
2
{
3
  public int compare(Person o1, Person o2) {
4
    // your code goes here
5
  }
6
}

Complete the compare() method in the class above as described below. The method takes as a parameter two objects of type Person named o1 and o2.

  • If o1 and o2 are both null, return 0.
  • If o1 is null, return -1.
  • If o2 is null, return 1.
  • If the last name in o1 is less than the last name in o2, return -1.
  • If the last name in o1 is greater than the last name in o2, return 1.
  • If the last name in o1 is equal to the last name in o2, return 0.

Your Answer:

x
 
1
int compare(Person o1, Person o2)
2
{
3
    
4
}
5

Feedback

Your feedback will appear here when you check your answer.