hashMap的hashCode() 和equal()的使用


hashMap的hashCode() 和equa()的使用
 
在java的集合中,判斷兩個對象是否相等的規則是:
1,判斷兩個對象的hashCode是否相等
    如果不相等,認為兩個對象也不相等,完畢
    如果相等,轉入2
2,判斷兩個對象用equals運算是否相等
    如果不相等,認為兩個對象也不相等
    如果相等,認為兩個對象相等 

復制代碼
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import android.app.Activity;
import android.os.Bundle;


public class TestCollectionActivity extends Activity {
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
        
        Set<Person> hashSet = new HashSet<Person>();
        hashSet.add(new Person("張先生", 12121212));
        hashSet.add(new Person("張太太", 12121213));
        hashSet.add(new Person("張先生", 12121210));
        hashSet.add(new Person("網先生", 12121210));
        hashSet.add(new Person("網先生", 12121210));
        hashSet.add(new Person("張先生", 12121210));
        /** 最后結果輸出為:
         *       張先生 12121212
            張太太 12121213
            網先生 12121210
            張先生 12121210
            
            如果不添加hashCode()和equals(),所有person成員都將正常輸出
            添加hashCode和equals之后,若a.hashCode() = b.hashCode且equals返回為true,此時原先的成員將被替代,
            導致了上面的結果輸出
        */
        
        Iterator<Person> it = hashSet.iterator();
        while(it.hasNext()) {
            Person person = it.next();
            System.out.println(person.getName() + " " + person.getId_card());
        }
        
    }
    
    public class Person {
        private String name;
        private long id_card;
        public Person(String name, long id_card) {
            this.name = name;
            this.id_card = id_card;
        }
        
        public long getId_card(){
            return id_card;
        }
        
        public String getName() {
            return name;
        }
        
        public int hashCode() {
            int result = 1;
            result = (int)(id_card ^(id_card>>32));
            return result;
//            final int PRIME = 31;
//            int result = 1;
//            result = PRIME * result + (int)(id_card ^ (id_card >>32));//long型數據取(int)位
//            result = PRIME * result + ((name == null) ? 0 : name.hashCode());
//            return result;
        }
        
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            final Person other = (Person) obj;
            if (id_card != other.id_card)
                return false;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }
    }
}
復制代碼



hashCode()和equal()由輸出情況可得知:添加hashCode()和equals()之后,若a.hashCode() = b.hashCode且equals返回為true,此時原先的成員將被替代,導致了上面的結果輸出。

   hashCode用於快速判斷兩個對象是否相等,如果相等,則根據equal的返回值確定是否覆蓋,equal()返回true則覆蓋。

 

下面是補充:

=====================================
1、 為什么要重載equal方法?
答案:因為Object的equal方法默認是兩個對象的引用的比較,意思就是指向同一內存,地址則相等,否則不相等;如果你現在需要利用對象里面的值來判斷是否相等,則重載equal方法。
2、 為什么重載hashCode方法?
答案:一般的地方不需要重載hashCode,只有當類需要放在HashTable、HashMap、HashSet等等hash結構的集合時才會重載hashCode,那么為什么要重載hashCode呢?就HashMap來說,好比HashMap就是一個大內存塊,里面有很多小內存塊,小內存塊里面是一系列的對象,可以利用hashCode來查找小內存塊hashCode%size(小內存塊數量),所以當equal相等時,hashCode必須相等,而且如果是object對象,必須重載hashCode和equal方法。
3、 為什么equals()相等,hashCode就一定要相等,而hashCode相等,卻不要求equals相等?
答案:1、因為是按照hashCode來訪問小內存塊,所以hashCode必須相等。
            2、HashMap獲取一個對象是比較key的hashCode相等和equal為true。
之所以hashCode相等,卻可以equal不等,就比如ObjectA和ObjectB他們都有屬性name,那么hashCode都以name計算,所以hashCode一樣,但是兩個對象屬於不同類型,所以equal為false。
4、 為什么需要hashCode?
1、 通過hashCode可以很快的查到小內存塊。
2、 通過hashCode比較比equal方法快,當get時先比較hashCode,如果hashCode不同,直接返回false。

 

微信公眾號【黃小斜】大廠程序員,互聯網行業新知,終身學習踐行者。關注后回復「Java」、「Python」、「C++」、「大數據」、「機器學習」、「算法」、「AI」、「Android」、「前端」、「iOS」、「考研」、「BAT」、「校招」、「筆試」、「面試」、「面經」、「計算機基礎」、「LeetCode」 等關鍵字可以獲取對應的免費學習資料。 

 

 

                     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM