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...

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...