What happens if hashcode() method returns constant value and equals() method returns false?

The¬†hashcode() method invokes and finds the bucket number if same same bucket is returned to objects then it checks the equality of the object by invoking equals() method. That’s why it is recommended to override both the methods.

If constant value is returned from hashcode() and equals() return false then each element will be stored to hash based collection even if they are equal. As we are returning same hash value for each object here then all the elements will be stored in same bucket. Because we forcefully saying that objects are different by returning false from equals() method.

package mypack;

public class Customer {
	private int id;
	@Override
	public int hashCode() {
		return id;
	}
	
	public boolean equals(Object obj){
		return false;
	}
	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