java - 使用 HashMap 的 hashCode() 方法

标签 java hashmap hashcode

如果我要自定义 HashMap,我是否必须重写 hashCode() 方法?

UPD:例如:

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());

    }

}

最佳答案

如果您要使用 ,则必须重写 A 类的 hashCode()equals() A 作为 HashMap 中的键,需要另一种形式的相等性而不是引用相等性。

从 Java 7 开始实现 hashcode() 的一个小技巧:使用 Objects#hash(Object...)
例如:

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

  @Override
  public int hashcode() {
    return Objects.hash(attr1, attr2, /* ... , */ attrn);
  }
}

关于java - 使用 HashMap 的 hashCode() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23780310/

相关文章:

java - 接口(interface)内的 toString、hashcode 和 equals 方法

java - sparql 查询药物相互作用。小错误

java - spring中bean类的无效属性 'datasource'

rust - 如何获取包含在 Arc<> 和 RwLock<> 中的 Rust HashMap<> 的长度?

java - 如何访问未知的类方法

java - "Normalizing"BigDecimal 的哈希码 : howto?

java - App Engine 上的 getObjectById

java - 你能在 Java 中锁定本地对象吗?

java - 有趣的 HashMap 实现(build 1.7.0_25-b17)

java - Java HashMap的机制