重写equals()与hashCode()方法。当两个对象因为某种逻辑比较的时候,调用对象的比较方法。在散列中,以hashCode对对象进行排列等情况下都要重写对象的这两个方法:
以下Copy网上比较全面的例子
- 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;
- }
- }
如当散列中的对象Key木有复写hashCode方法,很容易找不到该Key所对应的值,如:
- public class Factory {
- private String product;
- public void setProduct(String product) {
- this.product = product;
- }
- public String getProduct() {
- return product;
- }
- public Factory(String produc) {
- this.product=produc;
- }
- @Override
- public boolean equals(Object obj) {
- if (obj==this) {
- return true;
- }
- if (!(obj instanceof Factory)) {
- return false;
- }
- Factory factory=(Factory) obj;
- return this.product==factory.product;
- }
- @Override
- public int hashCode() {
- return super.hashCode();
- }
- }
- HashMap<Factory,String> map=new HashMap<Factory, String>();
- map.put(new Factory("产品1"), "product1");
- System.out.println(map.get(new Factory("产品1"))); //返回null
这是因为散列中第一次put进去的Key的hashCode与获取的key的hashCode不是同一个int值。