简要说明下:
重写equals,一般都需要重写Object.hashCode方法,因为ObjectA.equals(ObjectB)时,按理说:ObjectA.hashCode() == ObjectB.hashCode()。
但是重写equals,不重写hashCode方法,会导致2个Object相等了,但是hashCode不等,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相等对象必须具有相等的哈希码。
代码:
比如,构建一个people类,比较2个people类是否相等
1、构建people类
public class People {
private String s1;
private int hash = 0;
public String getS1() {
return s1;
}
public void setS1(String s1) {
this.s1 = s1;
}
/**
* @param s1
*/
public People(String s1) {
super();
this.s1 = s1;
}
}
2、 重写equals方法
public class People {
private String s1;
private int hash = 0;
public String getS1() {
return s1;
}
public void setS1(String s1) {
this.s1 = s1;
}
/**
* @param s1
*/
public People(String s1) {
super();
this.s1 = s1;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof People && this.s1 != null && obj != null) {
char[] cs = this.s1.toCharArray();
int count = 0;
while (count < cs.length) {
if (cs[count] == ((People) obj).getS1().charAt(count)) {
count++;
continue;
}
return false;
}
return true;
} else {
return false;
}
}
}
3、重写hashCode方法,然后测试
public class People {
private String s1;
private int hash = 0;
public String getS1() {
return s1;
}
public void setS1(String s1) {
this.s1 = s1;
}
/**
* @param s1
*/
public People(String s1) {
super();
this.s1 = s1;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof People && this.s1 != null && obj != null) {
char[] cs = this.s1.toCharArray();
int count = 0;
while (count < cs.length) {
if (cs[count] == ((People) obj).getS1().charAt(count)) {
count++;
continue;
}
return false;
}
return true;
} else {
return false;
}
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
if (hash == 0) {
char[] cs = this.s1.toCharArray();
for (int i = 0; i < cs.length; i++) {
hash += i * 31 + cs[i];
}
}
return hash;
}
public static void main(String[] args) {
People p1 = new People("w11kk");
People p2 = new People("w11kk");
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
System.out.println(p1.equals(p2));
}
}
4、得出的结果为:
741
741
true
结果和预期的一样,起始重写这2个方法比较灵活,equals达到自己想要的预期效果就行,hashCode保证不同的Object,equals时,hashCode也需要相同