使用ComparisonChain而不是Objects.qual()&& Objects.equal()...和Guava有什么好处

Nim*_*sky 12 java equals guava comparisonchain

我刚刚开始使用google的Guava集合(ComparisonChainObjects).在我的pojo我覆盖了equals方法,所以我先做了这个:

return ComparisonChain.start()
         .compare(this.id, other.id)
         .result() == 0;
Run Code Online (Sandbox Code Playgroud)

但是,我意识到我也可以使用它:

return Objects.equal(this.id, other.id);
Run Code Online (Sandbox Code Playgroud)

我没有看到比较链何时更好,因为你可以轻松添加更多条件,如下所示:

return Objects.equal(this.name, other.name) 
       && Objects.equal(this.number, other.number);
Run Code Online (Sandbox Code Playgroud)

如果您特别需要返回int,我可以看到的唯一好处.它有两个额外的方法调用(开始和结果),并且对于菜鸟来说更复杂.

我错过了ComparisonChain有明显的好处吗?

(是的,我也用适当的覆盖哈希码Objects.hashcode())

SLa*_*aks 20

ComparisonChain允许您通过比较多个属性(例如按多列排序网格)来检查对象是否小于或大于另一个对象.
它应该在实现时使用ComparableComparator.

Objects.equal 只能检查是否平等.


Lou*_*man 12

ComparisonChain用于帮助对象实现Comparable或Comparator接口.

如果您只是实现Object.equals(),那么您是正确的; Objects.equal就是您所需要的.但是,如果您正在尝试实现Comparable或Comparator - 正确 - 使用ComparisonChain比使用其他方法更容易.

考虑:

class Foo implements Comparable<Foo> {
   final String field1;
   final int field2;
   final String field3;

   public boolean equals(@Nullable Object o) {
      if (o instanceof Foo) {
         Foo other = (Foo) o;
         return Objects.equal(field1, other.field1)
             && field2 == other.field2
             && Objects.equal(field3, other.field3);
      }
      return false;
   }

   public int compareTo(Foo other) {
      return ComparisonChain.start()
         .compare(field1, other.field1)
         .compare(field2, other.field2)
         .compare(field3, other.field3)
         .result();
   }
 }
Run Code Online (Sandbox Code Playgroud)

而不是将compareTo实现为

 int result = field1.compareTo(other.field2);
 if (result == 0) {
   result = Ints.compare(field2, other.field2);
 }
 if (result == 0) {
   result = field3.compareTo(other.field3);
 }
 return result;
Run Code Online (Sandbox Code Playgroud)

...更不用说正确地做到这一点的诡计,这比你猜想的要高.(我已经看到了比你想象的更多比较混乱的方法.)