Skip to main content

What is equals() and hashCode() Method in Java? | What are use of equals() and hashCode() Method in Java

Java hashCode() and equals() Methods with Examples | When to use | How to Use

Java hashCode() and equals() Methods with Examples | When to use | How to Use

You already known that Object is root of all classes in Java.

So whenever we create any class in java then our class implicitly extends the Object class.

There are so many methods available in Object.

  • clone()
  • equals()
  • finalize()
  • getClass()
  • hashCode()
  • notify()
  • notifyAll()
  • toString()
  • wait()

Check out this Java doc above methods

Now in this article we talk about equals() and hashCode() method. so lets start.

So first question in your mind pop up that why i use equals and hashCode method so lets see answer of that first.

Why and in which condition we have to use equals() and hashCode() method in Java?

  • When we want to use Object as key in hashTable then we should use equals() and hashCode() methods in java.

equals() Method

In simple term, equals() method checks that one object is 'equals to' another object.

equals() method used to simply verify the equality of two objects. It's default implementation simply check the object references of two objects to verify their equality.

By default, two object are equals if and only if they are stored in same memory address.

for any non-null reference values x and y, equals() method returns true if only x and y refer to the same object (x == y has the value true).

Lets see example of default behavior of equals() method.

Example 1 :- Default implementation of equals() method

User.java
public class User {
    
    int id;
    String name;
    
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

EqualsAandHashcode.java
public class EqualsAandHashcode {

    public static void main(String[] args) {

        User user1 = new User(1, "user1");
        User user2 = new User(1, "user1");
       
        System.out.println(user1.equals(user2));
       
    }
}

Output :-
false

So you can seen in above example, that we declare two objects with same id and name, but when we check equals() of that we get output false. but in real time application we have to get true, because it is same object.

So now we override equals method and check what we get.

Example 2 :- Override equals() method.

User.java
public class User {
    
    int id;
    String name;
    
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

}

EqualsAandHashcode .java
public class EqualsAandHashcode {

    public static void main(String[] args) {

        User user1 = new User(1, "user1");
        User user2 = new User(1, "user1");
       
        System.out.println(user1.equals(user2));

    }

}

Output :-
true

Now after override equals method we get true for same object. so it is very important in real time java application that we should implement equals() method.

If you want to generate equals and hashCode method then right click on your eclipse and go to -> Source -> Generate hashCode() and equals().

For above example you can comment hashCode() method.

hashCode() Method

What is hashCode() method? Why we use hashCode() method in java?

The hashCode() mehod  of object is used when we use HashTable, HashMap and HashSet.

When inserting an object into hashtable we use a key. The hashcode of this key is calculated, and used to determine where to store the object internally.

When we need to lookup an object in a hashtable we also use a key. The hashcode of this key is calculated and used to determine where to search for an object.

So lets see example what happens if we does not use hashCode() method.

Example 3 :- Without overriding hashCode() method

public class User {
    
    int id;
    String name;
    
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    
    
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }

}

public class EqualsAandHashcode {

    public static void main(String[] args) {

        User user1 = new User(1, "user1");
        User user2 = new User(1, "user1");
       
        System.out.println(user1.equals(user2));
       
        Set<User> setOfUser = new HashSet<>();
        setOfUser.add(user1);
        setOfUser.add(user2);
       
        System.out.println(setOfUser);
       
    }

}

Output :-
true
[User [id=1, name=user1], User [id=1, name=user1]]

You know that Set does not contains duplicate value but in above example you can clearly see we got two object. So what happens when we use hashCode() method? so lets implement it.

Example 4 :- overriding hashCode() method in Java

public class User {
    
    int id;
    String name;
    
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
   
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }

}

public class EqualsAandHashcode {

    public static void main(String[] args) {

        User user1 = new User(1, "user1");
        User user2 = new User(1, "user1");
       
        System.out.println(user1.equals(user2));
       
        Set<User> setOfUser = new HashSet<>();
        setOfUser.add(user1);
        setOfUser.add(user2);
       
        System.out.println(setOfUser);
       
    }

}

Output :-
true
[User [id=1, name=user1]]

So after overriding hashCode() method we can clearly see we get only one object that have same id and name.

So, both equals() and hashCode() methods are important in our java real time application.

If you want to learn about equals() and hashCode() method, What is contract between them? Read out these articles. i also taken references from these articles and video.

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...