簡介
HashSet實現(xiàn)了Set接口,它不允許集合中有重復的值。HashSet是對HashMap的簡單包裝,對HashSet的函數(shù)調(diào)用都會轉(zhuǎn)換成合適的HashMap方法。
具體實現(xiàn)
public boolean add(Object o)方法用來在Set中添加元素
add()方法
public boolean add(E e) {
//對map的封裝,如果map.put(e, PRESENT)==null則返回true
return map.put(e, PRESENT)==null;
}
從上面源碼可以看出HashSet的add()方法最終調(diào)用HashMap的put()方法,具體實現(xiàn)可以看[Java 8之HashMap理解]
HashSet如何確保元素不重復
前面[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():如果我們對象沒有重寫hashCode方法,那么將使用HashMap自身實現(xiàn)的hashCode方法
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//HashMap自身實現(xiàn)的hashCode方法
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
//HashMap自身實現(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;
}
所以我們將對象存儲在HashSet之前,要先確保對象重寫equals()和hashCode()方法,這樣才能比較對象的值是否相等,以確保set中沒有儲存相等的對象。如果我們沒有重寫這兩個方法,將會使用這個方法的默認實現(xiàn)。
上面通過equals()和hashCode()方法可以確保沒有存儲相等對象了。
當元素值重復時則會立即返回false,如果成功添加的話會返回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;
}
}
//存在重復的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,那么說明map.put(e, PRESENT)!=null,add()方法返回false
public boolean add(E e) {
//對map的封裝,如果map.put(e, PRESENT)==null則返回true
return map.put(e, PRESENT)==null;
}