Java - The equals and hashCode methods

java

http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/
https://www.sitepoint.com/how-to-implement-javas-hashcode-correctly/
http://www.javaworld.com/article/2074996/hashcode-and-equals-method-in-java-object---a-pragmatic-concept.html
https://www.tutorialspoint.com/java/java_string_hashcode.htm
http://tutorials.jenkov.com/java-collections/hashcode-equals.html
https://www.ibm.com/developerworks/java/library/j-jtp05273/index.html
http://programming.guide/java/overriding-hashcode-and-equals.html
http://programming.guide/java/when-to-override-equals.html
https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java

How can we implement the equals method?

class Client {
  private int id;
  public Client(int id) {
    this.id = id;
  }

  public boolean equals(Object obj) {
    Client other = (Client) obj;
    if (id != other.id) {
      return false;
    }
    return true;
  }

  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    return result;
  }
}

Why do we need to implement the hashCode method?

The implementation of hash code decides the effectiveness of Hashing. A good hashing function evenly distribute objects into different groups or buckets. A good hashCode method should have the following properties:

  1. if obj1.equals(obj2) is true, then obj1.hashCode() should be equals to obj2.hashCode()
  2. obj.hashCode() should return the same value when run multiple times if values of obj have not change.
  3. if obj1.equals(obj2) is false, it is not required that obj1.hashCode() is not equal to obj2.hashCode(). Two unequal objects MIGHT have the same hashCode.

The hashCode method is used when the object is put into a HashMap.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License