用HashSet的add方法談hashcode和equals方法重寫,hashsethashcode

來源:互聯網
上載者:User

用HashSet的add方法談hashcode和equals方法重寫,hashsethashcode

    本文主要通過用HashSet的add方法講一下hashCode和equals方法重寫。錯誤的地方望指正。

 1.瞭解HashSet的add方法

瞭解一個方法的好辦法是看源碼,所以先看源碼

private transient HashMap<E,Object> map;// Dummy value to associate with an Object in the backing Mapprivate static final Object PRESENT = new Object();public boolean add(E e) {return map.put(e, PRESENT)==null;}

 

 由上面可以知道HashSet裡面是用的HashMap處理,add方法其實是用了map的put方法

 1 transient Entry<K,V>[] table; 2 transient int modCount; 3 public V put(K key, V value) { 4         if (key == null) 5             return putForNullKey(value);                                              6         int hash = hash(key);                                                        7         int i = indexFor(hash, table.length); 8         for (Entry<K,V> e = table[i]; e != null; e = e.next) { 9             Object k;10             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {11                 V oldValue = e.value;12                 e.value = value;13                 e.recordAccess(this);14                 return oldValue;15             }16         }17         modCount++;18         addEntry(hash, key, value, i);19         return null;20  }

 

    table即前面已經存在的資料,這裡會將已存在的內容的key與當前key做比較,e.hash == hash && ((k = e.key) == key || key.equals(k)),其中hash是根據hashcode計算,一般情況下,hashCode一致,hash也是一樣的。如果比較的是true的話,將已存在的value改成新的。對於hashset其實就原值沒變只是在內部的hashmap的value重新放了new Object().

 2.例子

到這裡我想應該都知道,如何來重寫了。這裡簡單做一個例子。

public class UnlockGood {    public UnlockGood(){}    public UnlockGood(String skuNo, int wmsId,int count) {        super();        this.skuNo = skuNo;        this.count = count;        this.wmsId = wmsId;    }    //商品編碼    private String skuNo;    //數量    private int count;    //倉庫ID    private int wmsId;    public String getSkuNo() {        return skuNo;    }    public void setSkuNo(String skuNo) {        this.skuNo = skuNo;    }    public int getCount() {        return count;    }    public void setCount(int count) {        this.count = count;    }    public int getWmsId() {        return wmsId;    }    public void setWmsId(int wmsId) {        this.wmsId = wmsId;    }    @Override    public boolean equals(Object obj) {        UnlockGood good = (UnlockGood)obj;        if(this==obj){            return true;        }else if(this.getSkuNo().equals(good.getSkuNo())&&this.getWmsId()==good.getWmsId()){            good.setCount(good.getCount()+this.getCount());            return true;        }else{            return false;        }    }    @Override    public int hashCode() {        //隨便寫一個hashCode        return 1;    }}

上面是重寫的hashCode和equals方法,下面是main方法

        Set<UnlockGood> unlockgoods = new HashSet<UnlockGood>();        UnlockGood good =  new UnlockGood("a",1,2);        unlockgoods.add(good);        UnlockGood good1 = new UnlockGood("a",1,12);        unlockgoods.add(good1);        UnlockGood good2 = new UnlockGood("b",1,2);        unlockgoods.add(good2);        

 

這裡利用的是如果hash一致的時候,會調用equals方法,當然如果是同一個key就不會調用equals方法的。利用這個特性對原始值進行修改,達到自己想要的元素加入規則。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.