在做业务的时候经常会遇到需要对集合去重,最常用的就是HashSet。那HashSet是怎么实现的不重复存储的哪?各位看官往下看:
先看个最简单的构造方法
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
很明显,HashSet底层是hashmap存储的。借大神的话
HashSet 就是HashMap的马甲 -----someone
很形象哈。
再看看add方法
// Dummy value to associate with an Object in the backing Map
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object();
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
add方法的参数(要存储的value)作为HashMap的key,PRESENT(Object PRESENT = new Object();)作为固定value。
重点看key(敲黑板)
HashMap中的put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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;
}
}
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;
}
这里边有两个看点:
- HashMap中key存储是hash后的值,对于String类型的相同值的hash值是一致的(其他接触类型类似,自定义对象类型需要重写hashcode方法与equel方法)。换句话说相同的值在hashMap中的存储位置是一样的。
- 基于上一点来看看怎么存储重复值的。如下代码对于hashMap中已经存在的key,key不变,新value覆盖就value。对于HashSet而言新旧value都是PRESENT对象,所以set在存储的时候就不会重复。
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
所以hashset中存储的值输出的顺序和存储的先后顺序不一致,而是按照值的hash顺序输出。