自己编写HashCodeBuilder类
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()); } }
相关推荐
Roka 2020-06-28
xhpscdx 2020-05-17
chaigang 2020-02-25
歆萌 2020-02-02
chunianyo 2019-12-21
疯狂紫萧 2019-12-14
PHP淮北PHP00网 2013-09-17
QCkiss 2019-11-04
歆萌 2019-11-03
Kwong 2019-10-22
宇智波鼬 2018-08-30
zhrookie 2011-11-18
81423067 2015-06-02
wewoor 2015-12-27
lizaochengwen 2019-03-19
stSahana 2016-11-01