哈希表:散列表
冲突-解决 开散列
扩容需要注意的问题:需要重新哈希
实现简单哈希表(Integer)
//哈希桶
class HashBuck {
//结点类
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; //已经存放的元素的个数
public HashBuck() {
this.array = new Node[8];
}
//get方法(通过key值,获取value值)
public int get(int key) {
int index = key % array.length;
//遍历当前index下标的链表
Node cur = array[index];
while (cur != null) {
if (cur.key == key) {
return cur.val;
}
cur = cur.next;
}
return -1; //找不到的情况
}
//put方法
public void put(int key, int val) {
//1、找位置
int index = key % array.length;
//2、遍历当前Index下标 是不是有相同Key
Node cur = array[index];
while (cur != null) {
if (cur.key == key) {
//替换原来的值
cur.val = val;
return;
}
cur = cur.next;
}
//cur==null
Node node = new Node(key, val);
cur = array[index];
if (cur == null) {
array[index] = node;
} else {
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
this.usedSize++;
//0.75:HashMap的负载因子
if (loadFactor() >= 0.75) {
resize();
}
}
public double loadFactor() {
return this.usedSize*1.0/ array.length;
}
public void resize() {
Node[] newArray = new Node[array.length*2];
//遍历原来的数组
for (int i = 0; i < array.length; i++) {
Node cur = array[i];
while (cur != null) {
Node curNext = cur.next;
//计算当前key在新数组当中的下标
int index = cur.key% newArray.length;
Node curN = newArray[index];
if (curN == null) {
newArray[index] = cur;
} else {
//找出新数组当前下标的尾巴
while (curN.next != null) {
curN = curN.next;
}
curN.next = cur;
}
//每个节点都是尾插法,插入后要将next置为null
cur.next = null;
cur = curNext;
}
}
array = newArray;
}
}
public class TestDemo {
public static void main(String[] args) {
HashBuck hashBuck = new HashBuck();
hashBuck.put(1,11);
hashBuck.put(2,22);
hashBuck.put(3,33);
hashBuck.put(17,177); //1 //1
hashBuck.put(24,244); //0 //8
hashBuck.put(15,155); //15
System.out.println();
}
}