X1040: Complete compareTo() 1

For the Person class below to implement the Comparable interface, you must complete the compareTo method.

  public class Person implements Comparable<Person> {
    // ...
    public Person (String f, String l) { ... }
    public String getFirst() { ... }
    public String getLast() { ... }
    public String toString() { return getLast()+", "+getFirst(); }

    public int compareTo(Person other) {
      // to be completed
    }
  }

Complete the compareTo() method in the class above as described below. The method takes as a parameter another Person, named other.

  • If other is null, return -1.
  • If the last name in this object is less than the last name in other, return -1.
  • If the last name in this object is equal to the last name in other, return 0.
  • If the last name in this object is greater than the last name in other, return 1.

Please note that the compareTo defined in String returns <0, 0 or >0. However, this routine makes explicit that it must return -1, 0, or 1.

Your Answer:

Feedback

Your feedback will appear here when you check your answer.