java中Object对象重写equal()函数与hashcode()函数,先要明白equal()函数对于任何非空引用值仅当两个值引用同一个对象时此方法才返回true,此处不解释如果不明白可以在本网站搜索equal与==的区别。重写时必须保证hashcode()函数的常规规范,该规范声明相等对象必须具有相同的哈希码。
如何实现hashcode哈希码相等,具体代码如下:
1)当obj1.equals(obj2)为true时,obj1.hashCode() == obj2.hashCode()必须为true
2)当obj1.hashCode() == obj2.hashCode()为false时,obj1.equals(obj2)必须为false
代码演示,具体代码如下:package com.yoodb;
public class Number {
private String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.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;
Number other = (Number) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
return true;
}
public Number(String a) {
super();
this.a = a;
}
}
总结:
hashcode()函数是用于散列数据的快速存取,如利用HashSet/HashMap/Hashtable类来存储数据时,都是根据存储对象的hashcode值来进行判断是否相同的。