今天在做一个笔试题时,竟然要求手写一个HashMap,当场就懵了......
不过话说回来,自己实现的过程中,也能加深对哈希表的理解。
直接上代码。
class MyHashMap{
static class Node{
int key;
String value;
Node next;
Node(int _key, String _value){
key = _key;
value = _value;
}
}
Node[] nodes = new Node[10010];
//添加
public void put(int key, String value){
//获取存放的位置
int idx = getIndex(key);
Node ioc = nodes[idx], tmp = ioc;
if(ioc != null){
//如果当前位置已经有值了,用链表存储起来(拉链法)
Node prev = null;
while(tmp != null){
if(tmp.key == key){
tmp.value = value;
return;
}
prev = tmp;
tmp = tmp.next;
}
tmp = prev;
}
//存储
Node node = new Node(key, value);
if(tmp != null){
tmp.next = node;
}else{
nodes[idx] = node;
}
}
//查找
public String get(int key){
//获取存放的位置
int idx = getIndex(key);
Node ioc = nodes[idx];
if(ioc != null){
while(ioc != null){
//遍历当前位置的值,找到key相同的数返回
if(ioc.key == key){
return ioc.value;
}
ioc = ioc.next;
}
}
return "_EMPTY_";
}
//删除
public void remove(int key){
//获取存放的位置
int idx = getIndex(key);
Node ioc = nodes[idx];
if(ioc != null){
Node prev = null;
while(ioc != null){
//删除key后,整理当前位置的链表
if(ioc.key == key){
if(prev != null){
prev.next = ioc.next;
}else{
nodes[idx] = ioc.next;
}
return;
}
prev = ioc;
ioc = ioc.next;
}
}
}
//根据hash值计算可以存放的位置
int getIndex(int key){
int hash = Integer.hashCode(key);
hash ^= (hash >>> 16);
return hash % nodes.length;
}
}