目录
一、哈希表简述
哈希表(Hash table,也叫散列表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。
1.哈希表的底层结构
JDK1.8版本之前--
哈希表底层使用的是数组+链表
JDK1.8版本及以后--
哈希表底层引入了红黑树
2.哈希表的新增过程
下面以HashSet为例,我们来说一下它的新增原理,在调用add方法时,我们点进去看看它的源码是怎么写的。
public class Demo {
public static void main(String[] args) {
HashSet<Integer> hs = new HashSet<Integer>();
hs.add(1);
hs.add(3);
}
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public V put(K key, V value) {
return putVal(hash(key), key, value, 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;
}
}
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;
}
1.创建一个默认长度为16,默认加载因子为0.75的数组,数组名table
通过源码我们可以看到,HashSet底层是一个Node类型的数组,第一次新增时,数组为null,会继续调用resize()方法给table赋值,再进入到resize()方法里面,可以看到数组被赋值默认长度,而默认长度为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
2.根据元素的哈希值,模上数组的长度计算出元素存入位置的下标。
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
3.判断当前位置是否为null,如果为null则直接存入
if ((tab = table) == null || (n = tab.length) == 0)
4.如果存入的位置不为null,表示有元素,此时调用equals方法比较属性值,如果一样则不存,如果不一样则存入。
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);
二、哈希冲突
1.哈希冲突的概念
当两个元素计算出来的哈希值一样时,他们在数组中的下标也一样,就好像买票,一个座位同时卖给了两个人,这时候就产生了冲突。
2.哈希冲突的解决办法
(1)拉链法
当发生哈希冲突时,会将新的元素存入计算好的索引值位置,将旧元素挂在新元素的下面(Node链表)。
(2)开放地址法
发生哈希冲突时,新的元素会继续寻找下一块未被占用的索引位置,并在该位置存放。
三、总结
1. JDK1.8底层优化:
底层使用数组、链表、红黑树的结合体。
当挂在下面的元素过多,不利于添加也不利于查询,所以在JDK8以后,当链表长度超过8的时候,自动转换为红黑树。
2.哈希表的优缺点:
优点:
1.无论数据有多少,处理起来都特别的快
2.能够快速的进行增删改查
缺点:
1.哈希表中的元素没有顺序
2.哈希表中的元素不可以重复