What happens if hashcode() method returns random value and equals() method returns true?

In Java hash based collection uses hashing technique for storing objects. So while you working with hash based collection like HashSet,HashMap,ConcurrentHashMap etc then you need to override following 2 methods of Object class.

  1. hashcode()
  2. equals()

How Hash based collection works?

  1. It calculates hashcode of each element to be stored and then find the appropriate location where the element will be stored. As you know that if same hashcode retured for more than one element then it uses linked list for storing both of them.
  2. After finding the hashcode of element and getting the index or bucket number where element to be stored. It checks whether any element is there in that index if found then it invokes equals() method to check whether both of the element is equal or not.

so in simple way we can say that hashcode() invokes first and if the element is already there in that index then equals() method will be invoked for checking equality of elements.

 

If constant value is returned from hashcode() and equals() return false then each element will be stored to hash based collection.

In our case if hashcode() return different value for each object then wouldn’t invoke the equality of objects so every element will be added to collection.

package mypack;

import java.util.Random;

public class Customer {
 
	private int id;
	@Override
	public int hashCode() {
		return new Random().nextInt();
	}
	
	public boolean equals(Object obj){
		return true;
	}
	private String name;
	
	Customer(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;
	}
	
}

package mypack;
import java.util.HashSet;
public class HashSetExample {
 public static void main(String[] args) {
 HashSet<Customer> set = new HashSet<Customer>();
 set.add(new Customer(1,"Raj"));
 set.add(new Customer(1,"Raj"));
 set.add(new Customer(1,"Raj"));
 set.add(new Customer(1,"Raj"));
 System.out.println("Size :"+set.size());
 }
}

Output

 Output
 Size :4

Leave a Reply