0

Do I have to override hashCode() method, if I'm going to customize HashMap?

UPD: For example:

import java.util.HashMap;
import java.util.Objects;

/**
 *
 * @author dolgopolov.a
 */
public class SaltEntry {

    private long time;
    private String salt;

    /**
     * @return the time
     */
    public long getTime() {
        return time;
    }

    /**
     * @param time the time to set
     */
    public void setTime(long time) {
        this.time = time;
    }

    /**
     * @return the salt
     */
    public String getSalt() {
        return salt;
    }

    /**
     * @param salt the salt to set
     */
    public void setSalt(String salt) {
        this.salt = salt;
    }

    public boolean equals(SaltEntry o) {
        if (salt.equals(o.getSalt()) && time == o.getTime()) {
            return true;
        } else {
            return false;
        }
    }

    public int hashCode() {
        return Objects.hash(String.valueOf(salt + time));
    }

    public static void main(String[] args) {
        SaltEntry se1 = new SaltEntry(), se2 = new SaltEntry();
        se1.setSalt("1");
        se2.setSalt("1");
        se1.setTime(1);
        se2.setTime(1);
        HashMap<String, SaltEntry> hm = new HashMap<String, SaltEntry>();
        hm.put("1", se1);
        hm.put("2", se2);
        System.out.println(hm.get("1").getSalt());

    }

}
5
  • Short answer is yes. It is always advisable to override hashCode() Commented May 21, 2014 at 10:19
  • 2
    hashCode and equals methods should be overridden in the class used as key for the Map. Commented May 21, 2014 at 10:19
  • @SaifAsif careful. Look at the usage of Map. Commented May 21, 2014 at 10:20
  • @LuiggiMendoza Aahh correct ! I overlooked the key part. Commented May 21, 2014 at 10:22
  • 1
    @LuiggiMendoza: Only if you need a form of equality other than reference equality... Commented May 21, 2014 at 10:22

1 Answer 1

4

You have to override both hashCode() and equals() of the class A if you're going to use A as key in HashMap and need another form of equality than reference equality.

A little trick to implements hashcode() since Java 7: use Objects#hash(Object...).
For example:

public class A {
  Object attr1, attr2, /* ... , */ attrn ;

  @Override
  public int hashcode() {
    return Objects.hash(attr1, attr2, /* ... , */ attrn);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Check which class is used for the key.
Also, note that Objects is available since Java 7. If you're working on a prior version, you have to find another way to implement hashCode.
@LuiggiMendoza Right ! I'm going to edit my answer, thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.