如果我要自定义hashCode()
,是否必须覆盖HashMap
方法?
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());
}
}
答案 0 :(得分:4)
如果您要hashCode()
作为equals()
中的关键字,则必须覆盖课程A
的{{1}}和A
需要另一种形式的平等而不是参照平等。
自Java 7以来实现HashMap
的一个小技巧:使用hashcode()
例如:
Objects#hash(Object...)