標籤:方法 根據 bsp span col pre 相等 over str
1. hashCode1.1 基本概念
hashCode是JDK根據對象的地址算出來的一個int數字(對象的雜湊碼值),代表了該對象再記憶體中的儲存位置。
hashCode()方法是超級類Object類提供的一個方法,所有類都可以對該方法進行重寫。
1.2 為什麼重寫equals()方法要重寫hashCode()方法
hashCode()相等是兩個對象相等的必要非充分條件。
equals()相等是兩個對象相等的充要條件。
重寫equals()方法一定要重寫hashCode()方法是為了提升效率,初步通過hashCode()判斷是否相等,相等之後再通過equals()中的別的方式判斷是否相等
2. equals()方法
為保證程式健壯性,在重寫equals方法時需滿足以下情況:
- 自反性 :A.equals(A)要返回true
- 對稱性:如果A.equals(B)返回true,則B.equals(A)也要返回true
- 傳遞性:如果A.equals(B)為true,B.equals(C)為true,則A.equals(C)也要為true, 相當於如果A = B, B = C ,那麼A = C
- 一致性:只要A、B對象的狀態沒有改變,A.equals(B)必須始終返回true
- A.equals(null) 要返回false
3. 練習
設計一個類Person含有height、weight、age和blood是整數屬性,實現hashcode方法,將四個屬性編排到一個整數中作為hashCode()和equals()方法
1 public class Person { 2 public int height; 3 public int weight; 4 public int age; 5 public int blood; 6 7 public int getHeight() { 8 return height; 9 }10 11 public void setHeight(int height) {12 this.height = height;13 }14 15 public int getWeight() {16 return weight;17 }18 19 public void setWeight(int weight) {20 this.weight = weight;21 }22 23 public int getAge() {24 return age;25 }26 27 public void setAge(int age) {28 this.age = age;29 }30 31 public int getBlood() {32 return blood;33 }34 35 public void setBlood(int blood) {36 this.blood = blood;37 }38 39 public Person(int height, int weight, int age, int blood) {40 this.height = height;41 this.weight = weight;42 this.age = age;43 this.blood = blood;44 }45 46 @Override47 public boolean equals(Object o) {48 49 if(this.hashCode() == o.hashCode()){50 return true;51 }52 return false;53 }54 55 @Override56 public int hashCode() {57 58 int i = (height << 24 & 0xff) | (weight << 16 & 0xff) | (age << 8 & 0xff) | blood;59 60 return i;61 }62 63 public static void main(String[] args) {64 Person p1 = new Person(1, 2, 3, 5);65 Person p2 = new Person(1, 3, 3, 4);66 System.out.println(p1.equals(p2));67 }68 69 }
Java重寫hashCode()和equals()方法