簡(jiǎn)介
HashSet實(shí)現(xiàn)了Set接口,它不允許集合中有重復(fù)的值。HashSet是對(duì)HashMap的簡(jiǎn)單包裝,對(duì)HashSet的函數(shù)調(diào)用都會(huì)轉(zhuǎn)換成合適的HashMap方法。
具體實(shí)現(xiàn)
public boolean add(Object o)方法用來(lái)在Set中添加元素
add()方法
public boolean add(E e) {
//對(duì)map的封裝,如果map.put(e, PRESENT)==null則返回true
return map.put(e, PRESENT)==null;
}
從上面源碼可以看出HashSet的add()方法最終調(diào)用HashMap的put()方法,具體實(shí)現(xiàn)可以看[Java 8之HashMap理解]
HashSet如何確保元素不重復(fù)
前面[Java 8之HashMap理解]中提到
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
//key.hashCode():如果我們對(duì)象沒有重寫hashCode方法,那么將使用HashMap自身實(shí)現(xiàn)的hashCode方法
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//HashMap自身實(shí)現(xiàn)的hashCode方法
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
//HashMap自身實(shí)現(xiàn)的equal方法
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
所以我們將對(duì)象存儲(chǔ)在HashSet之前,要先確保對(duì)象重寫equals()和hashCode()方法,這樣才能比較對(duì)象的值是否相等,以確保set中沒有儲(chǔ)存相等的對(duì)象。如果我們沒有重寫這兩個(gè)方法,將會(huì)使用這個(gè)方法的默認(rèn)實(shí)現(xiàn)。
上面通過(guò)equals()和hashCode()方法可以確保沒有存儲(chǔ)相等對(duì)象了。
當(dāng)元素值重復(fù)時(shí)則會(huì)立即返回false,如果成功添加的話會(huì)返回true。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//存在重復(fù)的key了,直接返回oldValue
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//根據(jù)上面的代碼返回的oldValue,那么說(shuō)明map.put(e, PRESENT)!=null,add()方法返回false
public boolean add(E e) {
//對(duì)map的封裝,如果map.put(e, PRESENT)==null則返回true
return map.put(e, PRESENT)==null;
}