Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava Vs Apache Commons Hash/Equals builders

I was wondering what are key differences between Guava vs Apache Commons with respect to equals and hashCode builders.

equals:

Apache Commons:

public boolean equals(Object obj) {
    if (obj == null) { return false; }
    if (obj == this) { return true; }
    if (obj.getClass() != getClass()) { return false; }
    MyClass other = (MyClass) obj;
    return new EqualsBuilder()
            .appendSuper(super.equals(obj))
            .append(field1, other.field1)
            .append(field2, other.field2)
            .isEquals();
}

Guava:

public boolean equals(Object obj) {
    if (obj == null) { return false; }
    if (obj == this) { return true; }
    if (obj.getClass() != getClass()) { return false; }
    MyClass other = (MyClass) obj;
    return Objects.equal(this.field1, other.field1)
            && Objects.equal(this.field1, other.field1);
}

hashCode:

Apache Commons:

public int hashCode() {
    return new HashCodeBuilder(17, 37)
            .append(field1)
            .append(field2)
            .toHashCode();
}

Guava:

public int hashCode() {
    return Objects.hashCode(field1, field2);
}

One of the key difference appears to be improved code readability with Guava's version.

I couldn't find more information from https://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained. It would be useful to know more differences (especially any performance improvement?) if there are any.

like image 251
Abhishek Avatar asked Jun 25 '15 18:06

Abhishek


Video Answer


1 Answers

I'd call this difference "existence". There are EqualsBuilder and HashCodeBuilder in Apache Commons and there are no builders in Guava. All you get from Guava is a utility class MoreObjects (renamed from Objects as there's such a class in JDK now).

The advantages of Guava's approach come from the non-existence of the builder:

  • it produces no garbage
  • it's faster

The JIT compiler can possibly eliminate the garbage via Escape Analysis and also the associated overhead. Then they get equally fast as they do exactly the same.

I personally find the builders slightly more readable. If you find not using them better, then Guava is surely the right thing for you. As you can see, the static methods are good enough for the task.

Note also that there's also a ComparisonChain which is a sort of Comparable-builder.

like image 101
maaartinus Avatar answered Sep 29 '22 09:09

maaartinus