Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding hashCode with a class with two generics fields

I am implementing a class Pair to use it as a key with two-values for a HashMap. I use generics to keep the types of the fields variable. I managed to write the biggest part of the code:

public class Pair<L, R>
{
    private L left;
    private R right;


    Pair(L left, R right)
    {
        this.left = left;
        this.right = right;
    }


    public L getLeft()
    {
        return left;
    }


    public R getRight()
    {
        return right;
    }


    public void setLeft(L left)
    {
        this.left = left;
    }


    public void setRight(R right)
    {
        this.right = right;
    }


    @Override
    public boolean equals(Object obj)
    {
        if (obj instanceof Pair< ? , ? >)
        {
            Pair< ? , ? > pair = (Pair< ? , ? >)obj;
            return left.equals(pair.getLeft()) && right.equals(pair.getRight());
        }
        return false;
    }

    @Override
    public String toString()
    {
        return "Pair " + Integer.toHexString(hashCode()) + ": (" + left.toString() + ", " + right.toString()
               + ")";
    }
}

My problem is to create proper hashCode method, which definitely delivers the same hashcode for equal objects, and different hashcode for different objects. Some hints?

like image 544
Danny Lo Avatar asked Jun 26 '14 14:06

Danny Lo


People also ask

Can 2 strings generate the same hashCode?

If two string objects are equal, the GetHashCode method returns identical values. However, there is not a unique hash code value for each unique string value. Different strings can return the same hash code.

Can two values have same hashCode?

1) If two objects are equal (i.e. the equals() method returns true), they must have the same hashcode. 2) If the hashCode() method is called multiple times on the same object, it must return the same result every time. 3) Two different objects can have the same hash code.

Can we override and return same hashCode for two different objects What is the contract between hashCode and equals () method?

If two objects are equal(according to equals() method) then the hashCode() method should return the same integer value for both the objects. But, it is not necessary that the hashCode() method will return the distinct result for the objects that are not equal (according to equals() method).


1 Answers

Don’t reinvent the wheel.

Just use return Objects.hash(left, right);

like image 91
Holger Avatar answered Oct 16 '22 05:10

Holger