What is the benefit of using ComparisonChain over Objects.equal() && Objects.equal() ... with Guava

Viewed 14756

I have just started using google's Guava collection (ComparisonChain and Objects). In my pojo I am overiding the equals method, so I did this first:

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

However, I then realized that I could also use this :

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

And I fail to see when comparison chain would be better as you can easily add further conditions like so:

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

The only benefit I can see if you specifically need an int returned. It has two extra method calls (start and result) and is more complex to a noob.

Are there obvious benefits of ComparisonChain I missing ?

(Yes, I am also overriding hashcode with appropriate Objects.hashcode())

4 Answers

I would be careful when using Guava's ComparisonChain because it creates an instance of it per element been compared so you would be looking at a creation of N x Log N comparison chains just to compare if you are sorting, or N instances if you are iterating and checking for equality.

I would instead create a static Comparator using the newest Java 8 API if possible or Guava's Ordering API which allows you to do that, here is an example with Java 8:

import java.util.Comparator;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsLast;

private static final Comparator<DomainObject> COMPARATOR=Comparator
  .comparingInt(DomainObject::getId)
  .thenComparing(DomainObject::getName,nullsLast(naturalOrder()));

@Override
public int compareTo(@NotNull DomainObject other) {
  return COMPARATOR.compare(this,other);
}

Here is how to use the Guava's Ordering API: https://github.com/google/guava/wiki/OrderingExplained

Related