xiaoguanmeizi 2007-03-14
jakarta-commons-lang已经实现了HashCodeBuilder类,据闻在Hibernate中出错,所以还是选择了自己实现,编码思想来源于Effectivejava一书。而且0依赖。
import java.lang.reflect.Array; public class HashCodeBuilder { public HashCodeBuilder() { } private int result = 17; public HashCodeBuilder append(boolean field) { result = 37 * result + (field ? 1 : 0); return this; } public HashCodeBuilder append(byte field) { result = 37 * result + (int) field; return this; } public HashCodeBuilder append(char field) { result = 37 * result + (int) field; return this; } public HashCodeBuilder append(short field) { result = 37 * result + (int) field; return this; } public HashCodeBuilder append(int field) { result = 37 * result + field; return this; } public HashCodeBuilder append(long field) { result = 37 * result + (int) (field ^ (field >>> 32)); return this; } public HashCodeBuilder append(float field) { result = 37 * result + Float.floatToIntBits(field); return this; } public HashCodeBuilder append(double field) { append(Double.doubleToLongBits(field)); return this; } public HashCodeBuilder append(Object field) { if(field == null) result = 0; else if (field.getClass().isArray()) { for (int i = Array.getLength(field) - 1; i >= 0; i--) { append(Array.get(field, i)); } } else append(field.hashCode()); return this; } public int toHashCode() { return result; } @Override public int hashCode() { return result; } @Override public String toString() { return String.valueOf(result); } }
测试代码
public class MyBean { Long id; String name; char[] chars; public MyBean(Long id, String name, char[] chars) { super(); this.id = id; this.name = name; this.chars = chars; } @Override public int hashCode() { return new HashCodeBuilder().append(id) .append(name).append(chars).hashCode(); } public static void main(String[] args) { MyBean bean1 = new MyBean(Long.valueOf(10), "名称",new char[]{'a','b','c','d','e'}); MyBean bean2 = new MyBean(Long.valueOf(10), "名称",new char[]{'a','b','c','d','e'}); System.out.println("bean1.hashCode="+bean1.hashCode()); System.out.println("bean2.hashCode="+bean2.hashCode()); } }