本文主要通过用HashSet的add方法讲一下hashCode和equals方法重写。错误的地方望指正。
1.了解HashSet的add方法
了解一个方法的好办法是看源码,所以先看源码
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方法
transient Entry<K,V>[] table;
transient int modCount;
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
} 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方法的。利用这个特性对原始值进行修改,达到自己想要的元素加入规则。