Caesar Ralf Caesar Ralf - 2 months ago 8
Java Question

Why isn't there guava Objects.equal(Object, Object) to primitive types?

Why isn't there an

receiving as an argument each primitive type?

I know you can box the value via
#valueOf
or let each primitive be autoboxed, but don't you lose performance doing that? That's something that I've been wondering about for sometime.

Imagine I have something like

public class Foo {
private final int integerValue;
private final boolean booleanValue;
private final Bar bar;

public Foo(int integerValue, boolean booleanValue, Bar bar) {
this.integerValue = integerValue;
this.booleanValue = booleanValue;
this.bar = bar;
}

@SuppressWarnings("boxing")
@Override
public boolean equals(Object object) {
if (object instanceof Foo) {
Foo that = (Foo) object;

return Objects.equal(this.integerValue, that.integerValue)
&& Objects.equal(this.booleanValue, that.booleanValue)
&& Objects.equal(this.bar, that.bar);
}
return false;
}

// hashCode implementation using guava also.
}


Is this the best way to implement
equals
? The primitive values are going to be autoboxed, suffering (even if it's a little) a performance degradation. I could just use
==
for them, but for me it would break the "flow" of reading the equals method, turning it a little ugly. So I wonder why guava lib don't have an
Objects.equal
for each primitive type. Does someone know the answer?

EDIT

There's for the MoreObjects.toStringHelper overload for each primitive (but byte), that's one the reason I wondered about not having for
Objects#equal
. Also, using JB Nizet argument, it would turn the
equals
method safer because you can change
int
for
Integer
without having to worry about equal correctness.

Guava docs

Answer

I could just use == for them, but for me it would break the "flow" of reading the equals method, turning it a little ugly.

This is not a convincing enough reason to add an overload of that method for each primitive type to the Guava API - every method that an API exposes has to be documented, tested, and maintained. It doesn't make sense when the only advantage is aesthetics.

Comments