Java hashCode() and equals()

I realized the importance of equals() and hashCode() while trying to remove an element from a List. The method hashCode() returns an Integer value of an object which is generated by a hashing algorithm. Collection framework depends on this for various operations like finding elements, duplicates, etc...

Let's take a simple class Animal with name and age.

package io.ironman;

public class Animal {

    private final String animalName;
    private final Integer animalAge;

    public Animal(String animalName, Integer animalAge) {
        this.animalName = animalName;
        this.animalAge = animalAge;
    }

}

Time to add some animal data.

 Animal cow = new Animal("COW",5);
 Animal dog = new Animal("DOG",4);
 Animal cat = new Animal("CAT",7);

When we print the hashCode of each element we get the following result.

image.png

It's time to delete an element.

Animal cowCopy = new Animal("COW",5);
System.err.println("Remove status->"+animals.remove(cowCopy));
animals.stream().forEach(System.out::println);

image.png

The element was not removed and if we look at the hashCode of two objects, it differs and if we look into the docs of equals and hashCode it must be implemented for classes so that they produce the same hashcode for the same values.

image.png

The solution is to override equals and hashCode for the POJO we create.

package io.ironman;

import java.util.Objects;

public class Animal {

    private final String animalName;
    private final Integer animalAge;

    public Animal(String animalName, Integer animalAge) {
        this.animalName = animalName;
        this.animalAge = animalAge;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Animal animal = (Animal) o;
        return Objects.equals(animalName, animal.animalName) && Objects.equals(animalAge, animal.animalAge);
    }

    @Override
    public int hashCode() {
        return Objects.hash(animalName, animalAge);
    }

    @Override
    public String toString() {
        return "Animal{" +
                "animalName='" + animalName + '\'' +
                ", animalAge=" + animalAge +
                '}';
    }

}

image.png

That's hashCode and its importance in collection framework.