Design a HashMap without using any built-in hash table libraries.
Implement the MyHashMap class:
MyHashMap() initializes the object with an empty map. void put(int
key, int value) inserts a (key, value) pair into the HashMap. If the
key already exists in the map, update the corresponding value. int
get(int key) returns the value to which the specified key is mapped,
or -1 if this map contains no mapping for the key. void remove(key)
removes the key and its corresponding value if the map contains the
mapping for the key.
class MyHashMap {
//双值存储节点
private class Pair{
private int key;
private int value;
public Pair() {}
public Pair(int key, int value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
//设置哈希算法
private static final int BASE = 888;
//设链表数组
private LinkedList[] data;
//初始化
public MyHashMap() {
data = new LinkedList[BASE];
for (int i = 0; i < BASE; i++) {
data[i] = new LinkedList<Pair>();
}
}
//哈希函数
public int hash(int key){return key%BASE;}
//存值
public void put(int key, int value) {
int h = hash(key);
Iterator<Pair> iterator = data[h].iterator();
//顺着链表查找,找到就覆盖
while (iterator.hasNext()){
Pair pair = iterator.next();
if (pair.getKey() == key) {
pair.setValue(value);
return;
}
}
//找不到,尾部新增
data[h].offerLast(new Pair(key,value));
}
//取值
public int get(int key) {
int h = hash(key);
Iterator<Pair> iterator = data[h].iterator();
while (iterator.hasNext()){
Pair pair = iterator.next();
//找到了,就返回
if (pair.getKey() == key) {
return pair.getValue();
}
}
//找不到-1
return -1;
}
//移除
public void remove(int key) {
int h = hash(key);
Iterator<Pair> iterator = data[h].iterator();
while (iterator.hasNext()){
Pair pair = iterator.next();
//找到了,移除
if (pair.getKey() == key) {
data[h].remove(pair);
return;
}
}
}
}