JAVA重寫hashCode通用方法(摘錄自《Effective Java》),重寫hashcode和equals

來源:互聯網
上載者:User

JAVA重寫hashCode通用方法(摘錄自《Effective Java》),重寫hashcode和equals

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);}}

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.