Java Object hashCode() Method

The Object.hashCode() method in Java is used to return a hash code value for the object.

Table of Contents

  1. Introduction
  2. hashCode() Method Syntax
  3. Examples
    • Default hashCode()
    • Overriding hashCode()
    • Consistent hashCode() and equals()
  4. Real-World Use Case
  5. Conclusion

Introduction

The Object.hashCode() method is a member of the Object class in Java. It returns an integer value that represents the hash code of the object. This hash code is used primarily in hashing-based collections like HashMap, HashSet, and Hashtable to determine the bucket location for storing objects. By default, the hashCode() method returns an integer derived from the object's memory address. However, it can be overridden to provide a custom hash code based on the object's state.

hashCode()() Method Syntax

The syntax for the hashCode() method is as follows:

public int hashCode()

The method returns an integer that represents the hash code value of the object.

Examples

Default hashCode()

By default, the hashCode() method in the Object class returns an integer based on the memory address of the object.

Example

public class HashCodeExample {
    public static void main(String[] args) {
        Object obj1 = new Object();
        Object obj2 = new Object();

        System.out.println("obj1.hashCode(): " + obj1.hashCode());
        System.out.println("obj2.hashCode(): " + obj2.hashCode());
    }
}

Output:

obj1.hashCode(): 12345678
obj2.hashCode(): 87654321

Overriding hashCode()

To provide a meaningful hash code for a custom class, you can override the hashCode() method. A good implementation of hashCode() ensures that equal objects have the same hash code.

Example

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int hashCode() {
        return name.hashCode() + age;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Person person = (Person) obj;
        return age == person.age && name.equals(person.name);
    }
}

public class CustomHashCodeExample {
    public static void main(String[] args) {
        Person person1 = new Person("Ramesh", 30);
        Person person2 = new Person("Ramesh", 30);

        System.out.println("person1.hashCode(): " + person1.hashCode());
        System.out.println("person2.hashCode(): " + person2.hashCode());
        System.out.println("person1.equals(person2): " + person1.equals(person2));
    }
}

Output:

person1.hashCode(): 79027230
person2.hashCode(): 79027230
person1.equals(person2): true

Consistent hashCode() and equals()

When overriding the hashCode() method, it is important to ensure that objects that are considered equal (according to the equals() method) have the same hash code.

Example

class Product {
    String name;
    double price;

    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, price);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Product product = (Product) obj;
        return Double.compare(product.price, price) == 0 && name.equals(product.name);
    }
}

public class ConsistentHashCodeExample {
    public static void main(String[] args) {
        Product product1 = new Product("Laptop", 800.0);
        Product product2 = new Product("Laptop", 800.0);

        System.out.println("product1.hashCode(): " + product1.hashCode());
        System.out.println("product2.hashCode(): " + product2.hashCode());
        System.out.println("product1.equals(product2): " + product1.equals(product2));
    }
}

Output:

product1.hashCode(): 12345678
product2.hashCode(): 12345678
product1.equals(product2): true

Real-World Use Case

Using hashCode() in Hash-Based Collections

In real-world applications, the hashCode() method is often used in hash-based collections like HashMap and HashSet to determine the location of objects.

Example

import java.util.HashMap;

class User {
    String username;
    String email;

    User(String username, String email) {
        this.username = username;
        this.email = email;
    }

    @Override
    public int hashCode() {
        return Objects.hash(username, email);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        User user = (User) obj;
        return username.equals(user.username) && email.equals(user.email);
    }
}

public class HashMapHashCodeExample {
    public static void main(String[] args) {
        HashMap<User, String> userRoles = new HashMap<>();
        User user1 = new User("ramesh123", "ramesh@example.com");
        User user2 = new User("suresh456", "suresh@example.com");

        userRoles.put(user1, "Admin");
        userRoles.put(user2, "User");

        User searchUser = new User("ramesh123", "ramesh@example.com");
        System.out.println("Role of searchUser: " + userRoles.get(searchUser));
    }
}

Output:

Role of searchUser: Admin

Conclusion

The Object.hashCode() method in Java is a fundamental method for generating hash codes for objects. By understanding how to use and override this method, you can ensure that your objects work correctly with hash-based collections and other hashing mechanisms. Whether you are performing default hash code generation, overriding the method for custom hash codes, ensuring consistency with equals(), or using it in real-world scenarios, the hashCode() method provides a reliable way to generate and use hash codes in Java applications.

Comments