Example of hashCode() and equals() in Java
March 07, 2013
On this page we will provide example of hashCode() and equals() in Java. In java Collection like Set and Map key needs unique object. If we are creating a class and creating objects, and on the basis of some parameters we want to say that these objects are same then how it is decided that two objects are same or different. In Object class, there are two methods equals() and hashCode().
hashCode:
hashCode() returns the hash code of an object. We override this method to fulfill our requirement. hashCode is declared likepublic int hashCode() { int hashno = 7; hashno = 13 * hashno + (name == null ? 0 : name.hashCode()); return hashno; }
equals:
In String class equals checks two string for its value. This is the definition for the String class. We can define equals method according to our requirement.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 return same value for two objects, then it is necessary that hashCode must be same.
Find the below 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