HashSet中的元素是不重复的,那么是何如做好这点呢?下面就结合源码来看这个问题(源码基于JDK1.8)。
1、HashSet.add()方法
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
HashSet中的数据存储在一个Map中,其提供的操作也是依赖这个map来实现的。
add方法只是调用map的put方法来添加元素,并没有什么过滤逻辑。因此去重逻辑应该在map的put方法中。
2、HashMap.put()方法。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//获取key的hashcode值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//map内数组判空
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//(n - 1) & has