Java - hashCode() method

What is hashCode() method?

A hash code is an integer value computed for a piece of information using an algorithm.

A hash code is also called a hash sum, a hash value, or a hash.

The algorithm to compute an integer based on information is called a hash function.


The Object class has a hashCode() method that returns an int, which is the hash code of the object.

The default implementation of hashCode() method returns the memory address of the object into an integer.

You can override the implementation in your class.


Here are the rules that you must follow when you override the hashCode() method.

Suppose there are two object references, x and y.

  • If x.equals(y) returns true, x.hashCode() and y.hashCode() must return the same integer value.
  • If x.hashCode() is equal to y.hashCode(), it is not necessary that x.equals(y) returns true.
  • If hashCode() method is called on the same object multiple times on the same run, the method must return the same integer value.

java.lang.Objects contains a hash() method that computes the hash code for any number of values of any type.

The following code shows how to implement the hashCode() method.


class Book {
  private String title = "Java tutorial";
  private String author="";
  private int pageCount = 1234;
  private boolean hardCover = true;
  private double price = 0.0;

  public int hashCode() {
    int hash = 37;
    int code = 0;

    // Use title//from w ww.  jav  a  2s  .c  om
    code = (title == null ? 0 : title.hashCode());
    hash = hash * 59 + code;

    // Use author
    code = (author == null ? 0 : author.hashCode());
    hash = hash * 59 + code;

    // Use pageCount
    code = pageCount;
    hash = hash * 59 + code;

    // Use hardCover
    code = (hardCover ? 1 : 0);
    hash = hash * 59 + code;
    // Use price
    long priceBits = Double.doubleToLongBits(price);
    code = (int) (priceBits ^ (priceBits >>> 32));
    hash = hash * 59 + code;

    return hash;

public class Main {
  public static void main(String[] args) {
    Book b = new Book();