A2oz

What is equals and hashCode in Java?

Published in Java Programming 2 mins read

In Java, the equals() and hashCode() methods are crucial for determining object equality and efficient storage in data structures like hash tables.

equals() Method

The equals() method is used to compare two objects for equality. By default, it checks if two objects refer to the same memory location. However, you can override this method to define your own equality logic based on the object's attributes.

Example:

class Person {
    String name;
    int age;

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

In this example, two Person objects are considered equal if they have the same name and age.

hashCode() Method

The hashCode() method generates an integer value representing an object's hash code. This hash code is used in hash-based data structures like HashMap and HashSet to efficiently store and retrieve objects.

Important Points:

  • If two objects are equal according to the equals() method, their hash codes should be the same.
  • If two objects have the same hash code, they are not necessarily equal.
  • It is crucial to override both equals() and hashCode() methods consistently to maintain the integrity of hash-based data structures.

Example:

class Person {
    // ... (other attributes and equals() method)

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

This example uses the Objects.hash() method to generate a hash code based on the name and age attributes.

Practical Insights

  • Data Structures: Implementing equals() and hashCode() correctly is essential for using hash-based data structures like HashMap and HashSet effectively.
  • Performance: Overriding these methods can improve the performance of your code, especially when dealing with large datasets.
  • Immutability: For immutable objects, it's generally easier to implement equals() and hashCode() as they are not subject to change.

Related Articles