标签:
1.何时需要重写equals()
import java.util.Arrays; /** * 类描述:set集合针对String 类型和8大基础数据类型过滤掉重复数据, * * 如果存放的是其他类型对象,则需要重写hashCode方法和equals方法,当equals 比较相等时,则会去比较hashCode值 * * hashCode的值 如果一致的话,则不会存进set */ 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 == null || !(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) && Arrays.equals(ints, unit.ints) && Arrays.equals(units, unit.units); } public int hashCode() { final int prime = 37; int result = 17; result = prime * result + (int) ashort; result = prime * result + (int) achar; result = prime * result + (int) abyte; result = prime * result + (abool ? 0 : 1); result = prime * result + (int) (along ^ (along >>> 32)); result = prime * result + Float.floatToIntBits(afloat); long tolong = Double.doubleToLongBits(adouble); result = prime * result + (int) (tolong ^ (tolong >>> 32)); result = prime * result + aObject.hashCode(); result = prime * result + intsHashCode(ints); result = prime * 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; } }
标签:
原文地址:http://www.cnblogs.com/kofxxf/p/4218501.html