《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

相关文章
相关标签/搜索