# 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1614956680761/FZCCw98GE.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1614956916662/H1djYa-dT.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](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#method_detail) of equals and hashCode it must be implemented for classes so that they produce the same hashcode for the same values.


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1614957779489/F43eEKjm7.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1614957978716/rph44q9uT.png)

That's hashCode and its importance in collection framework.

