• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Java | hashCode Method
  1. hashCode Method

  1. hashCode Method
    When implementing the hashCode method we should make sure that it's consistent and always return the same value for objects for which the equals method return true.

    The hashCode method is defined in the java.lang.Object class and returns the object internal address:
    public native int hashCode();
    The java.util.Objects class provides utility methods to get the hash code of an object or multiple objects:
    public static int hashCode(Object o) {
        return o != null ? o.hashCode() : 0;
    }
    public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }
    The java.util.Arrays class provides utility methods to get the hash code of an array of objects (including specific overloaded methods for each primitive type). It also provides a utility method to get a deep hash code of an array of objects (array of arrays).

    The following is a sample code that show how to implement the hashCode method. The code provide an implementation of the hashCode method using hashCode and hash methods of the java.util.Objects class.

    • Superclass "P":
      class P {
          Integer id = 1;
      
          @Override
          public int hashCode() {
              return Objects.hashCode(id);
          }
      }
    • Subclass "C":
      class C extends P {
          String code = "default";
      
          @Override
          public int hashCode() {
              return Objects.hash(super.hashCode(), code);
          }
      }
© 2025  mtitek