Example of hashCode() and equals() in Java

By Arvind Rai, 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()

Define equals() 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));
	}
}
Note:

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;
    }
}
EqualsAndHashCodeDemo.java
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());
    }
}
DemoClass has overridden hashCode and equals. So equality of two objects will be decided by equals and hashCode.
Output
size:1 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us