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?
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.
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.
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).
Don’t reinvent the wheel.
Just use return Objects.hash(left, right);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With