重写equals方法后记得把hashCode也重写一下,hashCode方法是返回java记录对象散列码,散列码尽量不要在对象值不同的情况下重复。看代码先
public class ETest
{
private String name;
private String[] info;
private int id;
private float money;
private boolean freeze;
private byte status;
private long saving;
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof ETest)
{
ETest et = (ETest) obj;
if (et.id == this.id
&& (et.name == this.name || et.name.equals(this.name))
&& (Arrays.equals(et.info, this.info))
&& et.money == this.money && et.freeze == this.freeze
&& et.status == this.status && et.saving == this.saving
)
{
return true;
}
}
return false;
}
/**
*
* {@inheritDoc}
*/
@Override
public int hashCode()
{
// 正整数常量,值为素数
int result = 17;
// 计算hashCode,37是素数
// 整数
result = 37 * result + id;
// 对象
result = 37 * result + objectHashCode(name);
// 浮点型
result = 37 * result + Float.floatToIntBits(money);
// boolean
result = 37 * result + (freeze ? 0 : 1);
// byte
result = 37 * result + (int) status;
// Long
result = 37 * result + (int) (saving ^ (saving >>> 32));
// 数组
result = 37 * result + arrayHashCode(info);
return result;
}
int objectHashCode(Object obj){
if (obj == null)
{
return 0;
}
return obj.hashCode();
}
int arrayHashCode(Object[] objs)
{
int result = 0;
if (objs == null)
{
return result;
}
for (Object o : objs)
{
result += objectHashCode(o);
}
return result;
}
public ETest(String name, String[] info, int id, float money,
boolean freeze, byte status, long saving)
{
super();
this.name = name;
this.info = info;
this.id = id;
this.money = money;
this.freeze = freeze;
this.status = status;
this.saving = saving;
}
}
测试
public class Main
{
public static void main(String[] args)
{
ETest t1 = new ETest(null, new String[]{null,"dd"}, Integer.MAX_VALUE, Integer.MIN_VALUE, false, (byte) 0, 0);
ETest t2 = new ETest(null, new String[]{null,"dd"}, Integer.MAX_VALUE, Integer.MIN_VALUE, false, (byte) 0, 0);
Set<ETest> set = new HashSet<ETest>();
set.add(t1);
set.add(t2);
System.out.println(set.size());
}
}