我刚刚开始使用 google 的 Guava 集合(ComparisonChain 和 Objects)。在我的 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
允许您通过比较多个属性(例如按多列对网格进行排序)来检查一个对象是小于还是大于另一个对象。
它应该在实现 Comparable
或 Comparator
时使用。
Objects.equal
只能检查是否相等。
关于java - 使用 ComparisonChain over Objects.equal() && Objects.equal() ... with Guava 有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6942096/