Equals and HashCode

Consider the below example,
It’s a simple java class with one String field “key”. Inside the Main() method, We have created a HashMap and use this class object as a key and store a string as value.

Then we try to retrieve the value from that HashMap with that object. As this class does not override the hashCode() method, so invoking the hashCode() method on this class object will produce a different hashCode. So we would not able to retrieve the value with that object.

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.util.HashMap;
import java.util.Map;

public class Ckey {

    private String key;

    public Ckey(String key) {
        this.key = key;

    public String getKey() {
        return key;

    public void setKey(String key) {
        this.key = key;

    public String toString() {
        return new ToStringBuilder(this)
                .append("Ckey", key)

    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        Ckey keyMap = (Ckey) o;

        return new EqualsBuilder()
                .append(key, keyMap.key)

      /*  @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37)

    public static void main(String[] args) {
        Map hashMap = new HashMap();
        Ckey k1 = new Ckey("Key1");
        hashMap.put(k1, "key1");
        //Try to retrive the value with the same Key. You will end with null.since the hashCode are not implemented.
        // So invoking the hashCode will produce a default code which is different for every call. So you will not get the value
        System.out.println(hashMap.get(new Ckey("Key1")));

As per the contract
1) If two objects are equal, then they must have the same hash code.
2) If two objects have the same hash code, they may or may not be equal.

If you dont override the equals() method, then the compare operation will be failed. Hence it will return a Null value. So we should override both these methods to avoid these kind of issues

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s