Example of hashCode() and equals() in Java
November 14, 2023
On this page, we will discuss using Java hashCode()
and equals()
methods. In Java Collection like Set
and Map
, key needs to be a unique object. To decide if two objects of a class are same, we need to override hashCode()
and equals()
method.
hashCode()
hashCode()
returns the hashcode of an object. We override this method to create custom hashcode.
public int hashCode() { int hashno = 7; hashno = 13 * hashno + (name == null ? 0 : name.hashCode()); return hashno; }
equals()
Defineequals()
method to decide equality between two objects.
public boolean equals(final Object obj) { if (obj == null) { return false; } final DemoClass cb = (DemoClass) obj; if (this == cb) { return true; } else { return (this.name.equals(cb.name) && (this.age == cb.age)); } }
1. For two objects, if hashCode is same, then it is not necessary that
equals()
method should return same value.2. If
equals
method return same value for two objects, it is necessary that hashCode must be same for those objects.Find the example.
DemoClass.java
package com.concretepage; import java.util.HashSet; import java.util.Set; class DemoClass { public final String name; public final int age; DemoClass(final String name, final int age) { this.name = name; this.age = age; } @Override public boolean equals(final Object obj) { if (obj == null) { return false; } final DemoClass cb = (DemoClass) obj; if (this == cb) { return true; } else { return (this.name.equals(cb.name) && (this.age == cb.age)); } } @Override public int hashCode() { int hashno = 7; hashno = 13 * hashno + (name == null ? 0 : name.hashCode()); return hashno; } }
public class EqualsAndHashCodeDemo { public static void main(final String[] args) throws Exception { final Set<DemoClass> s = new HashSet<DemoClass>(); final DemoClass ob1 = new DemoClass("ABC", 15); final DemoClass ob2 = new DemoClass("ABC", 15); // Added two objects s.add(ob1); s.add(ob2); System.out.println("size:" + s.size()); } }
Output
size:1