Why should a Java class implement comparable?

后端 未结 10 633
忘掉有多难
忘掉有多难 2020-11-22 13:14

Why is Java Comparable used? Why would someone implement Comparable in a class? What is a real life example where you need to implement comparable

10条回答
  •  伪装坚强ぢ
    2020-11-22 13:34

    An easy way to implement multiple field comparisons is with Guava's ComparisonChain - then you can say

       public int compareTo(Foo that) {
         return ComparisonChain.start()
             .compare(lastName, that.lastName)
             .compare(firstName, that.firstName)
             .compare(zipCode, that.zipCode)
             .result();
       }
    

    instead of

      public int compareTo(Person other) {
        int cmp = lastName.compareTo(other.lastName);
        if (cmp != 0) {
          return cmp;
        }
        cmp = firstName.compareTo(other.firstName);
        if (cmp != 0) {
          return cmp;
        }
        return Integer.compare(zipCode, other.zipCode);
      }
    }
    

提交回复
热议问题