Search code examples
javahashmaphashcodekeyvaluepair

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?


Solution

  • Don’t reinvent the wheel.

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