《Effective JAVA學習筆記》之 compareTo()

class Person implements Comparable<Person> {
  String firstName;
  String lastName;
  int birthdate;
 
  // Compare by firstName, break ties by lastName, finally break ties by birthdate
  public int compareTo(Person other) {
    if (firstName.compareTo(other.firstName) != 0)
      return firstName.compareTo(other.firstName);
    else if (lastName.compareTo(other.lastName) != 0)
      return lastName.compareTo(other.lastName);
    else if (birthdate < other.birthdate)
      return -1;
    else if (birthdate > other.birthdate)
      return 1;
    else
      return 0;
  }
}
  • 老是實現泛型版本 Comparable 而不是實現原始類型 Comparable 。由於這樣能夠節省代碼量和減小沒必要要的麻煩。html

  • 只關心返回結果的正負號(負/零/正),它們的大小不重要。java

  • Comparator.compare()的實現與這個相似。api

  • 參考:java.lang.Comparableoracle

相關文章
相關標籤/搜索