WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Expert · question 62 of 100

How do you implement a custom hashCode() method in Java Collections, and what are some use cases for doing so?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

In Java, the hashCode() method is used to generate a hash code for an object, which is an integer value that represents the object. The hash code is used by many collection classes to determine the index of an object in a collection, such as a HashMap or HashSet.

When two objects are equal according to the equals() method, they must have the same hash code. However, two objects with the same hash code may not necessarily be equal.

To implement a custom hashCode() method in Java, you should follow the following guidelines:

The hashCode() method should return an int value. The hashCode() method should take into account all fields used in the equals() method. If two objects are equal, their hash codes must be the same. If a field used in the equals() method can have a null value, make sure to handle it properly in the hashCode() method to avoid a NullPointerException.

Here is an example implementation of a custom hashCode() method for a simple Person class:

public class Person {
    private String name;
    private int age;

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

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Person)) {
            return false;
        }
        Person other = (Person) obj;
        return Objects.equals(name, other.name) \&\& age == other.age;
    }

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

In this implementation, the hashCode() method uses the Objects.hash() method to generate a hash code based on the name and age fields of the Person object. The Objects.hash() method is a convenient way to generate a hash code for multiple fields, and automatically handles null values.

One use case for implementing a custom hashCode() method is when you have a class that will be used as a key in a HashMap or HashSet, and the default implementation of hashCode() (which simply returns the memory address of the object) is not suitable for your purposes. By implementing a custom hashCode() method, you can ensure that objects of your class are properly indexed in the collection.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics