java重写equals和hashCode方法

重写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;@Overridepublic 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}*/@Overridepublic int hashCode(){// 正整数常量,值为素数int result = 17;// 计算hashCode,37是素数// 整数result = 37 * result + id;// 对象result = 37 * result + objectHashCode(name);// 浮点型result = 37 * result + Float.floatToIntBits(money);// booleanresult = 37 * result + (freeze ? 0 : 1);// byteresult = 37 * result + (int) status;// Longresult = 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());}}

,使用双手头脑与心灵的是艺术家,只有合作双手

java重写equals和hashCode方法

相关文章:

你感兴趣的文章:

标签云: