哈希桶背后的结构
冲突不严重时是数组+链表,冲突严重时是数组+链表+红黑树
初始化工作
//定义key-value节点
static class Node {
public int key;
public int val;
public Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
//哈希表底层是数组+链表+红黑树
public Node[] array;
//记录哈希桶的有效个数
public int usedSize;
//底层的默认负载因子是0.75
public static final float DEFAULT_LOAD_FACTORY = 0.75F;
public HashBuck() {
this.array = new Node[10];
this.usedSize = 0;
}
存储键值对
通过哈希函数求出插入的键值对存放的位置,并通过尾插法进行插入
/**
* 存放Key-value
* @param key 键
* @param val 值
*/
public void put(int key, int val) {
Node node = new Node(key, val);
//先根据Key定位到数组的位置,哈希函数:Hash = key % capacity
int index = key % array.length;
//遍历该位置背后的链表,是否存在相同的key,如果有就更新value,
// 否则尾插法(底层实现方式)
//如果该位置为空
addLast(array[index], node, index, array);
usedSize++;
//每次插入元素,要计算负载因子,超过0.75要扩容
if(loadFactor()) {
grow();
}
}
//尾插法
private void addLast(Node head, Node node, int index, Node[] array) {
Node cur = head;
if(cur == null) {
array[index] = node;
return;
}
Node parent = null;//单链表需要记录插入节点的前驱
while(cur != null) {
if(cur.key == node.key) {
cur.val = node.val;
}
parent = cur;
cur = cur.next;
}
parent.next = node;
}
每次添加一个键值对都要判断是否超过负载因子
//判断负载因子是否大于0.75
private boolean loadFactor() {
return (usedSize * 1.0 / array.length) >= DEFAULT_LOAD_FACTORY;
}
如果超过负载因子要进行扩容,扩容要注意重新计算哈希值
/**
* 重新扩容要重新哈希
*/
private void grow() {
Node[] newArray = new Node[2 * array.length];
//遍历数组,及其背后的链表
for (int i = 0; i < array.length; i++) {
Node cur = array[i];
while(cur != null) {
//记录老数组的cur的下一个节点
Node curNext = cur.next;
//新下标
int index = cur.key % newArray.length;
Node newNode = newArray[index];
addLast(newNode, cur, index, newArray);
//不能cur = cur.next,因为此时的cur是在新数组新下标的节点
cur = curNext;
}
}
this.array = newArray;
}
通过键获取值
/**
* 通过Key获取value值
* @param key
* @return
*/
public int get(int key) {
int index = key % array.length;
Node cur = array[index];
while(cur != null) {
if(cur.key == key) {
return cur.val;
}
cur = cur.next;
}
return -1;
}