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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...