兩個對象的hashcode相等並不能說明這兩個對象equals,由於hashcode必然存在hash衝突,不管機率高低,所以嚴格意義上的equals方法不能僅使用兩個對象的hashcode來判斷他們是否equals。apache
有些時候咱們須要重寫hashcode和equal方法。例如咱們須要將自定義類 點:point[x,y] 放入hashSet中或者判斷兩個點是否相同app
建議採用apache工具包commons.lang3.builder.EqualsBuilder和commons.lang3.builder.HashCodeBuilderide
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Point)) return false; Point that = (Point) o; return new EqualsBuilder().append(x,that.).append(y,that.y).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37).append(x).append(y).toHashCode(); }