Java中equals()与hashCode()的原理与设计
作者:网络转载 发布时间:[ 2012/12/10 9:51:51 ] 推荐标签:
5、符合上面的原则的equals与hashcode的示例代码
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;
}
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11