java - 使用 ComparisonChain over Objects.equal() && Objects.equal() ... with Guava 有什么好处

标签 java equals guava comparisonchain

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

return ComparisonChain.start()
         .compare(this.id, other.id)
         .result() == 0;

然而,我后来意识到我也可以使用这个:

return Objects.equal(this.id, other.id);

而且我看不出什么时候比较链会更好,因为您可以像这样轻松添加更多条件:

return Objects.equal(this.name, other.name) 
       && Objects.equal(this.number, other.number);

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

ComparisonChain 是否有我遗漏的明显好处?

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

最佳答案

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

Objects.equal 只能检查是否相等。

关于java - 使用 ComparisonChain over Objects.equal() && Objects.equal() ... with Guava 有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6942096/

相关文章:

java - 是否有与 Apache Commons CircularFifoBuffer 等效的 Guava?

java - 如何利用可选的 lambda 表达式

java - 如何在 Eclipse 中加载 Google Collections Library?

java - 使用 byaccj 构建 ast 时出错

java - Java 中的 Process.exitValue()

java - 解决这个对象初始化问题的正确方法是什么?

Java 11 - 如何覆盖 JVM 和系统内存中的敏感信息(也许使用 System.gc()?)

java - 为什么 Object.equals() 的实现没有使用 hashCode()?

java - 为什么我在java中的 boolean 测试总是失败?

java - 如何让 checkstyle 跳过 eclipse 生成的 equals() 和 hashcode() 方法?