最近List<实体>转HashSet去重,遇到了重写equals与hashcode的问题,记录一下:
这是Object类关于这两个方法的源码
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
可以看出,Object类默认的equals比较规则就是比较两个对象的内存地址。所以在进行去重时需重写equals
public class EntAlterListEntity {
private String altItem;
private Date altDate;
public String getAltItem() {
return altItem;
}
public void setAltItem(String altItem) {
this.altItem = altItem;
}
public Date getAltDate() {
return altDate;
}
public void setAltDate(Date altDate) {
this.altDate = altDate;
}
@Override
public boolean equals(Object o) {
if(this == o){
return true;
}
if(o == null){
return false;
}
if(getClass() != o.getClass()){
return false;
}
EntAlterListEntity entAlter = (EntAlterListEntity) o;
//altDate判断
if(altDate == null){
if(entAlter.altDate !=null){
return false;
}
}else{
if(altDate.compareTo(entAlter.altDate)!=0){
return false;
}
}
//altItem判断
if(!StringUtils.equals(altItem, entAlter.altItem)){
return false;
return true;
}
}
而hashcode是本地方法,java的内存是安全的,因此无法根据散列码得到对象的内存地址,但实际上,hashcode是根据对象的内存地址经哈希算法得来的。ArrayList是根据equals来判断是否包含,而不管hashCode是否不相等。而HashSet处理流程则不一样,先判断两个对象的hashCode方法是否一样,如果不一样,立即认为两个对象equals不相等,并不调用equals方法,当hashCode相等时,再根据equals方法判断两个对象是否相等(散列数据的快速存取)。即 hashCode 方法的常规协定:
(1)当obj1.equals(obj2)为true时,obj1.hashCode() == obj2.hashCode()必须为true
(2)当obj1.hashCode() == obj2.hashCode()为false时,obj1.equals(obj2)必须为false
那么,如何重写hashCode呢?
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (altItem== null ? 0 : altItem.hashCode());
result = 31 * result + (altDate== null ? 0 : altDate.hashCode());
return result;
}
生成一个 int 类型的变量 result,并且初始化一个值,比如17,然后对类中每一个重要字段,也就是影响对象的值的字段,也就是 equals 方法里有比较的字段,进行以下操作:a. 计算这个字段的值 filedHashValue = filed.hashCode(); b. 执行 result = 31 * result + filedHashValue;
为什么要使用31?,以下是String hashCode 方法的源码
/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using {@code int} arithmetic, where {@code s[i]} is the
* <i>i</i>th character of the string, {@code n} is the length of
* the string, and {@code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
减少乘积的冲突,并且可以被优化
* 左移 << : 左边的最高位丢弃,右边补全0(把 << 左边的数据*2的移动次幂)
* 右移 >> : 把>>左边的数据/2的移动次幂
* 无符号右移 >>> : 无论最高位是0还是1,左边补齐0
所以 : 31 * i = (i << 5) - i(左边 31*2=62,右边 2*2^5-2=62) - 两边相等,JVM就可以高效的进行计算啦