简介
HashSet实现了Set接口,它不允许集合中有重复的值。HashSet是对HashMap的简单包装,对HashSet的函数调用都会转换成合适的HashMap方法。
具体实现
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()方法最终调用HashMap的put()方法,具体实现可以看[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自身实现的hashCode方法
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//HashMap自身实现的hashCode方法
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
//HashMap自身实现的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中没有储存相等的对象。如果我们没有重写这两个方法,将会使用这个方法的默认实现。
上面通过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;
}
//根据上面的代码返回的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;
}
网友评论