本文主要通過用HashSet的add方法講一下hashCode和equals方法重寫。錯誤的地方望指正。
了解一個方法的好辦法是看源碼,所以先看源碼
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private 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().
到這裡我想應該都知道,如何來重寫了。這裡簡單做一個例子。
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方法的。利用這個特性對原始值進行修改,達到自己想要的元素加入規則。