- jasongreen
- 等级:
- 性别:
- 文章: 922
- 积分: 280
- 来自: 安徽
|
jakarta-commons-lang已经实现了HashCodeBuilder类,据闻在Hibernate中出错,所以还是选择了自己实现,编码思想来源于 Effective java 一书。而且0依赖。
java 代码
- 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);
- }
-
- }
测试代码
java 代码
- 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());
- }
- }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
返回顶楼 |
|
|
- v38
- 等级: 初级会员
- 文章: 7
- 积分: 40
|
jasongreen 写道:
jakarta-commons-lang已经实现了HashCodeBuilder类,据闻在Hibernate中出错,所以还是选择了自己实现,编码思想来源于 Effective java 一书。而且0依赖。
==========================
jakarta-commons-lang已实现的HashCodeBuilder类的错误没有把我们给折磨死~
|
返回顶楼 |
|
|
- jasongreen
- 等级:
- 性别:
- 文章: 922
- 积分: 280
- 来自: 安徽
|
我没有用过common-lang,不是太清楚,我最近在写crazyPOJO的项目,通过Annotation标志value field,然后根据value field生成hashCode,生成equals,生成clone,生成toString,生成toXML,生成toJSON,进行中,今天已经实现了,hashCode和equals,clone等方法,一会上传,大家试用一下
|
返回顶楼 |
|
|