Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java hashCode from multiple fields

Given a class like so:

class MyObject {
  private String id1;
  private String id2;

  @Override
  public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof MyObject)) {
        return false;
    }
    MyObject other = (MyObject) o;
    return id1.equals(other.id1) || id2.equals(other.id2);
  }
}

Notice that equality does not depend on both fields matching, either field works. What would be a suitable hashCode implementation for this class?

like image 859
mkohram Avatar asked Jul 17 '18 16:07

mkohram


People also ask

Can two values have same Hashcode in Java?

It is perfectly legal for two objects to have the same hashcode. If two objects are equal (using the equals() method) then they have the same hashcode. If two objects are not equal then they cannot have the same hashcode.

How does hashCode () method work in Java?

hashCode in Java is a function that returns the hashcode value of an object on calling. It returns an integer or a 4 bytes value which is generated by the hashing algorithm. The process of assigning a unique value to an object or attribute using an algorithm, which enables quicker access, is known as hashing.

What happens if hashCode for multiple keys is same?

When two unequal objects have the same hash value, this causes a collision in the hash table, because both objects want to be in the same slot (sometimes called a bucket).

Can two classes have same hashCode?

HashCode collisions Whenever two different objects have the same hash code, we call this a collision. A collision is nothing critical, it just means that there is more than one object in a single bucket, so a HashMap lookup has to look again to find the right object.


Video Answer


1 Answers

This is not a valid implementation of equals.

Specifically, it violates the transitivity requirement.

As such, you can't implement hashCode "correctly" either, aside from making all instances have the same hash code.

like image 116
Andy Turner Avatar answered Oct 12 '22 12:10

Andy Turner