package com.wei.mybatisflex;
import java.util.ArrayList;
import java.util.List;
/**
* 用数组实现哈希表
*/
public class ArrayToHash {
/**
* 键值对定义
*/
class Pair{
private int key;
private String val;
public Pair(int key, String val) {
this.key = key;
this.val = val;
}
}
private List<Pair> buckets;
public ArrayToHash(){
//初始化100个桶
buckets = new ArrayList<>();
for (int i = 0; i < 100; i++) {
buckets.add(null);
}
}
/**
* 哈希函数
*/
public int hashFunc(int key) {
int index = key % 100;
return index;
}
/**
* 查询操作
*/
public String get(int key) {
int index = hashFunc(key);
Pair pair = buckets.get(index);
if (pair == null){
return null;
}
return pair.val;
}
/**
* 添加操作
*/
public void insert(int key, String val) {
Pair pair = new Pair(key,val);
int index = hashFunc(key);
buckets.set(index,pair);
}
/**
* 删除操作
*/
public void delete(int key) {
int index = hashFunc(key);
buckets.set(index, null);
}
/**
* 修改
*/
public void update(int key, String val) {
int index = hashFunc(key);
Pair pair = new Pair(key,val);
buckets.set(index, pair);
}
/**
* 获取所有键值对
*/
public List<Pair> pairSet() {
ArrayList<Pair> pairs = new ArrayList<>();
for (Pair pair:buckets
) {
if (pair != null) {
pairs.add(pair);
}
}return pairs;
}
/**
* 获取所有键
*/
public List<Integer> KeySet() {
ArrayList<Integer> keys = new ArrayList<>();
for (Pair pair :buckets
) {
if (pair != null) {
keys.add(pair.key);
}
}return keys;
}
/**
* 获取所有值
*/
public List<String> ValueSet() {
ArrayList<String> vals = new ArrayList<>();
for (Pair pair :buckets) {
if (pair != null) {
vals.add(pair.val);
}
}return vals;
}
/**
* 打印哈希表
*/
public void print(){
for (Pair pair :
pairSet()) {
System.out.println(pair.key+"->"+pair.val);
}
}
/**
* 测试
*/
public static void main(String[] args) {
ArrayToHash hash = new ArrayToHash();
hash.insert(123, "34");
hash.insert(124, "35");
hash.insert(125, "36");
hash.insert(126, "37");
hash.insert(127, "38");
System.out.println("哈希表展示如下:");
hash.print();
System.out.println("==================");
String s = hash.get(23);
System.out.println("k=123对应的val值是:"+s);
System.out.println("==================");
hash.update(124, "99");
System.out.println("把key=124的值换成99");
hash.print();
System.out.println("==================");
hash.delete(124);
System.out.println("删除key=124所对应的值:");
hash.print();
}
}
运行结果展示: