Skip to content

Suggest to use Double.compare or Float.compare when ObjectEqualsForPrimitives is triggered on floating point primitives #4392

Closed
@findepi

Description

for a class like

public class DoubleLiteral
{
    private final double value;

    public DoubleLiteral(double value) { this.value = value; }

    @Override
    public boolean equals(Object o)
    {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        DoubleLiteral that = (DoubleLiteral) o;
        return Objects.equals(value, that.value);
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(value);
    }
}

ObjectEqualsForPrimitives' current suggestion is:

DoubleLiteral.java:[37,30] [ObjectEqualsForPrimitives] Avoid unnecessary boxing by using plain == for primitive types.
[ERROR]     (see https://errorprone.info/bugpattern/ObjectEqualsForPrimitives)
[ERROR]   Did you mean 'return (value == that.value);'?

That changes semantics -- different result when both compared values are NaN. Object Equals should be value based and generally should compare NaNs as equal.
It's probably worth noting that equals generated for Java record classes also compares NaN values as equal (as if Objects.equals was used).

Therefore ObjectEqualsForPrimitives should not suggest ==, but it should suggest Double.compare(...) == 0 instead.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions