JAVA重寫hashCode通用辦法(摘錄自《Effective Java》)。本站提示廣大學習愛好者:(JAVA重寫hashCode通用辦法(摘錄自《Effective Java》))文章只能為提供參考,不一定能成為您想要的結果。以下是JAVA重寫hashCode通用辦法(摘錄自《Effective Java》)正文
1. 初始化一個整形變量,為此變量賦予一個非零的常數值,比方int result = 17;
2. 選取equals辦法中用於比擬的一切域,然後針對每個域的屬性停止計算:
(1) 假如是boolean值,則計算f ? 1:0
(2) 假如是byte\char\short\int,則計算(int)f
(3) 假如是long值,則計算(int)(f ^ (f >>> 32))
(4) 假如是float值,則計算Float.floatToIntBits(f)
(5) 假如是double值,則計算Double.doubleToLongBits(f),然後前往的後果是long,再用規則(3)去處置long,失掉int
(6) 假如是對象使用,假如equals辦法中采取遞歸調用的比擬方式,那麼hashCode中異樣采取遞歸調用hashCode的方式。 否則需求為這個域計算一個范式,比方當這個域的值為null的時分,那麼hashCode 值為0
(7) 假如是數組,那麼需求為每個元素當做獨自的域來處置。假如你運用的是1.5及以上版本的JDK,那麼沒必要自己去 重新遍歷一遍數組,java.util.Arrays.hashCode辦法包括了8種根本類型數組和援用數組的hashCode計算,算法同上,
java.util.Arrays.hashCode(long[])的詳細完成:
public static int hashCode(long a[]) { if (a == null) return 0; int result = 1; for (long element : a) { int elementHash = (int)(element ^ (element >>> 32)); result = 31 * result + elementHash; } return result; }
example:
package com.kingdee.cloudhub.stat.domains; import java.util.Arrays; public class Person { private int age; private String name; private char sex; private String[] hoby; public Person(int age, char sex, String name, String[] hoby) { this.age = age; this.sex = sex; this.name = name; this.hoby = hoby; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public String[] getHoby() { return hoby; } public void setHoby(String[] hoby) { this.hoby = hoby; } public int hashCode() { int result = 1; result = 31 * result + age; result = 31 * result + sex; result = 31 * result + name.hashCode(); for(String s : hoby) { result = 31 * result + s.hashCode(); } return result; } public boolean equals(Object obj) { if(null == obj) return false; if(this == obj) return true; if (!(obj instanceof Person)) return false; Person p = (Person)obj; return this.age == p.age && this.sex == p.sex && this.name.equals(p.name) && Arrays.equals(this.hoby, p.hoby); } }