大佬们,为什么我重写了hashCode和equals方法,判断两个类相等为什么还是false
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (id != other.id)
return false;
return true;
}
如果id是字符串的话请使用equals方法比较,基本类型比较的话才直接用==,!=
首先,你不能使用你的类ProductA==你的类ProductB(==永远都是地址相比较),必须用ProductA.equals(ProductB)
2.不需要重写hashCode
3.你的Product的id如果不是基本类型,也必须equals
问答版主就是牛,从现在起只回论坛,不在踏入问答半步