推荐导航
一.hashCode和Equals相关代码
// Object类的方法
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
// String重写的
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;
}
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
// 自己写对象时自动生成的
public class Bean {
private String aa;
private String bb;
private int c;
@Override
public int hashCode() {
int result = aa != null ? aa.hashCode() : 0;
result = 31 * result + (bb != null ? bb.hashCode() : 0);
result = 31 * result + c;
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bean bean = (Bean) o;
if (c != bean.c) return false;
if (aa != null ? !aa.equals(bean.aa) : bean.aa != null) return false;
return bb != null ? bb.equals(bean.bb) : bean.bb == null;
}
}
1、如果两个对象equals相等,那么这两个对象的HashCode一定也相同
2、如果两个对象的HashCode相同,不代表两个对象就相同,只能说明这两个对象在散列存储结构中,存放于同一个位置