Home > Enterprise >  How to correctly implement equals(), hashCode() if the values are within a range of each other?
How to correctly implement equals(), hashCode() if the values are within a range of each other?

Time:01-18

The criteria is that equals() method where the objects are considered equal if the value of the double variable is within /- 10 of the other object's value of the double variable.

I'm not sure how to correctly implement hashCode() so that the hashCode would be equal if it satisfies the conditions of the equals() method.

I would really appreciate your input! Thanks!

public class Test 
{
    private double value;

    private boolean isEqualValues (final double valueOne, final double valueTwo)
    {
        if(valueOne == valueTwo)
        {
            return true;
        }
        else if((valueOne - valueTwo <= 10) &&
                (valueOne - valueTwo >= -10))
        {
            return true;
        }
        else
        {
            return false;
        }


    @Override
    public boolean equals(final Object o)
    {
        if (this == o)
        {
            return true;
        }
        if (o == null || getClass() != o.getClass())
        {
            return false;
        }

        Test test = (Test) o;

        if(isEqualValues(test.value, value))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //How to implement hashCode()
    @Override
    public int hashCode()
    {
        
        //unsure how to correctly implement hashCode() so that the hashCode would be equal if it 
        //satisfies the conditions of the equals() method above
        
    }
}

CodePudding user response:

There's no way to consistently implement this, since equals() demands transitivity:

It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

new Test(1), new Test(9) and new Test(14) would fail that test (assuming a trivial one-argument constructor that assigns its argument to value).

One way to work around that is to not check for the absolute distance, but "categorize" your objects using some formula, for example take the floor of value / 10 and compare that.

This way "close" values like new Test(9) and new Test(11) would compare as not-equal, but other than that you'd get a similar result to what you described.

CodePudding user response:

You can't and you shouldn't.

You should implement a comparator and do such operations using that.

  • Related