HashCode
表示对象的地址值,一般情况下,并不使用,但有些hash优化过程中,涉及较多,比如hashMap, 源码中用HashCode做散列标准
Equals
评判对象是否一致
如果重写Equals 却不重写hashCode 有什么问题呢?
package test;
import java.util.HashMap;
public class Test {
public static void main(String args[]) {
HashMap<Test1, String> map = new HashMap<>();
String codeWithUPCase = "123ABCD";
Test1 testWithUPCase = new Test1(codeWithUPCase);
map.put(testWithUPCase, codeWithUPCase);
String codeWithLowCase = "123abcd";
Test1 testWithLowCase = new Test1(codeWithLowCase);
map.put(testWithLowCase, codeWithLowCase);
System.out.println(testWithUPCase.equals(testWithLowCase));
System.out.println(map.get(testWithUPCase));
System.out.println(map.get(testWithLowCase));
}
}
class Test1 {
private String code;
@Override
public String toString() {
return "Test1 [code=" + code + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Test1 other = (Test1) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equalsIgnoreCase(other.code))
return false;
return true;
}
public Test1() {
super();
}
public Test1(String code) {
super();
this.code = code;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
结果
true
123ABCD
123abcd
显然不正确,至于原因呢?
第一 : 我设置的equals是忽略大小写比较,所以应该是相等的。
故第二次put应该会替换第一次的值。但显然结果未替换, 造成了问题。这一点在项目中很容易引发一系列问题。