在重新equals方法时为啥要重写hashCode方法?
重写的原则是:两个对象根据equals方法相等,则两个对象hashCode产生同样的整数结
果。
其实重写hashCode方法是为了保证一些基于散列的集合能正常工作,这样集合包括
(HahsMap,HashSet,HashTable)。因为此类集合是利用hash算法与equals来区分对象的等同性。比如:对类 Test重写了equals方法,没有重写hashCode方法,意味着当Test类的两个实例a和b,在逻辑上相同(a.equals(b)==true),但是两个实例的hashCode不同。当定义一个Map对象:
Map<Test,String> map=new HashMap<Test,String>();
map.put(a,"this is Test object");
此时若系统通过map.get(b);来获得“this is Test object”,但返回的确是null。这是因为
map对象将a对象放入一个散列桶中,而get方法却在另一个散列桶中查询,即便两个散列码同时在一个散列桶中,也会因为散列码不同而找不到。散列码不匹配就没有必要验证对象的等同性,所以此处找不到返回null。由此可见,重写hashCode方法是很有必要的,因为你不知道你定义的类不会被别人放入hash机制的集合中。
下面是重写equals和hashCode通用的方式:
此处摘录《Effective java》 和转载:http://zhangjunhd.blog.51cto.com/113473/71571/
示例:
package com.zj.unit;
import java.util.Arrays;
public class Unit {
private short ashort;
private char achar;
private byte abyte;
private boolean abool;
private long along;
private float afloat;
private double adouble;
private Unit aObject;
private int[] ints;
private Unit[] units;
public boolean equals(Object o) {
if (!(o instanceof Unit))
return false;
Unit unit = (Unit) o;
return unit.ashort == ashort
&& unit.achar == achar
&& unit.abyte == abyte
&& unit.abool == abool
&& unit.along == along
&& Float.floatToIntBits(unit.afloat) == Float
.floatToIntBits(afloat)
&& Double.doubleToLongBits(unit.adouble) == Double
.doubleToLongBits(adouble)
&& unit.aObject.equals(aObject)
&& equalsInts(unit.ints)
&& equalsUnits(unit.units);
}
private boolean equalsInts(int[] aints) {
return Arrays.equals(ints, aints);
}
private boolean equalsUnits(Unit[] aUnits) {
return Arrays.equals(units, aUnits);
}
public int hashCode() {
int result = 17;
result = 37 * result + (int) ashort;
result = 37 * result + (int) achar;
result = 37 * result + (int) abyte;
result = 37 * result + (abool ? 0 : 1);
result = 37 * result + (int) (along ^ (along >>> 32));
result = 37 * result + Float.floatToIntBits(afloat);
long tolong = Double.doubleToLongBits(adouble);
result = 37 * result + (int) (tolong ^ (tolong >>> 32));
result = 37 * result + aObject.hashCode();
result = 37 * result + intsHashCode(ints);
result = 37 * result + unitsHashCode(units);
return result;
}
private int intsHashCode(int[] aints) {
int result = 17;
for (int i = 0; i < aints.length; i++)
result = 37 * result + aints[i];
return result;
}
private int unitsHashCode(Unit[] aUnits) {
int result = 17;
for (int i = 0; i < aUnits.length; i++)
result = 37 * result + aUnits[i].hashCode();
return result;
}
}