核心问题:set如何实现的元素不重复?
HashSet源码解析
HashMap构造
底层就是实现一个HashMap
public HashSet() {
map = new HashMap<>();
}
add方法
add操作就是把元素作为key放入map中,每次存放一个present的值,这个值没有任何意义,每次存放会浪费空间。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
Map源码
put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
hash方法
static final int hash(Object key) {
int h;
//计算hash值,根据传入的对象类型调用不同的hash函数
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
putValue方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//tab存放 当前的哈希桶, p用作临时链表节点
Node<K,V>[] tab; Node<K,V> p; int n, i;
//table为null,初始化table长度
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//i是散列值,table[i]上没有数据,没有发生哈希碰撞。存放数据
if ((p = tab[i = (n - 1) & hash]) == null)
//table[i]上存放节点Node
tab[i] = newNode(hash, key, value, null);
//table[i]上有数据,发生哈希碰撞
else {
Node<K,V> e; K k;
//hash是节点p的属性
//先比较hash是否一样,在比较key是否一样,如果相同,记录当前的节点e。(后面覆盖value会用到)
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);
//当前节点的hash一致,但是key不同,则在当前节点.next插入一个节点,变为链表
else {
//遍历到链表尾部看是否有相同的key,没有则加,有则替换Node(后面替换value会用到)
for (int binCount = 0; ; ++binCount) {
//后面没有节点,可以创建节点,退出循环
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果追加节点后,binCount >=7(也就是8个节点的时候),则转化为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//当前节点后面有节点,并且这个节点和当前的节点的hash和key都相同则找到了要替换的节点位置,退出循环(已经在e = p.next中更新了节点)
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//p指向下一个节点,在前面的代码中e = p.next
p = e;
}
}
//如果e不是null,说明有需要覆盖的节点,
if (e != null) {
// existing mapping for key
//则覆盖节点值,并返回原oldValue
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//这是一个空实现的函数,用作LinkedHashMap重写使用。
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//更新size,并判断是否需要扩容--大于初始容量。
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
static final int TREEIFY_THRESHOLD = 8;
为什么要(n - 1) & hash?
我们一般对哈希表的散列很自然地会想到用hash值对length取模(即除法散列法),Hashtable中也是这样实现的,这种方法基本能保证元素在哈希表中散列的比较均匀,但取模会用到除法运算,效率很低,HashMap中则通过 (length-1)&hash 的方法来代替取模,同样实现了均匀的散列,但效率要高很多,这也是HashMap对Hashtable的一个改进。
为什么哈希表的容量一定要是2的整数次幂?
首先,length为2的整数次幂的话,(n - 1) & hash就相当于对length取模,这样便保证了散列的均匀,同时也提升了效率;
其次,length为2的整数次幂的话,为偶数,这样length-1为奇数,奇数的最后一位是1,这样便保证了(n - 1) & hash的最后一位可能为0,也可能为1(这取决于h的值),即与后的结果可能为偶数,也可能为奇数,这样便可以保证散列的均匀性,而如果length为奇数的话,很明显length-1为偶数,它的最后一位是0,这样(n - 1) & hash的最后一位肯定为0,即只能为偶数,这样任何hash值都只会被散列到数组的偶数下标位置上,这便浪费了近一半的空间,因此,length取2的整数次幂,是为了使不同hash值发生碰撞的概率较小,这样就能使元素在哈希表中均匀地散列。
静态内部类Node
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
//map底层实现是一个Node数组
transient Node<K,V>[] table;
node底层存储了key,value,以及hash值
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() {
return key; }
public final V getValue() {
return value; }
public final String toString() {
return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
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;
}
}
解答:
set底层是map实现,存放元素的时候,进行hash(key),如果重复的key会进行覆盖节点操作(实际上就是覆盖value操作),而value又是固定一样的,所以不存在重复元素。