起因
面试的时候不光问hashmap的原理,有些时候也会让你手下一下hashmap的put方法等,所以为了面试,可以提前写一下简单的hashmap,以至于面试真被问到了不会乱了手脚;
直接附上代码,注释很详细了
public class MyHashMap<K, V> {
//定义一个链表
static class Node<K, V> {
K key;
V value;
Node<K, V> next;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
}
//主打简便,扩容暂时先不写了,容量固定
private final static int CAPACITY = 1024;
Node<K, V>[] nodes = new Node[CAPACITY];
public void put(K key, V value) {
int idx = getIndex(key);
Node<K, V> cur = nodes[idx];
//代表此哈希槽是空的,直接创建一个新节点放进去
if (cur == null) {
nodes[idx] = new Node<>(key, value);
return;
}
//不是空,就说明有哈希冲突,寻找链表中的尾节点
Node<K, V> last = null;
while (cur != null){
if (cur.key == key){//如果key已经存在,那就直接覆盖
cur.value = value;
return;
}
last = cur;
cur = cur.next;
}
last.next = new Node<>(key, value);
}
public V get(K key) {
int idx = getIndex(key);
Node<K, V> cur = nodes[idx];
while (cur != null) {
if (cur.key == key) {
return cur.value;
}
cur = cur.next;
}
return null;
}
/**
* 返回删除目标节点的k,如果K不存在,返回null
* */
public K remove(K key){
int idx = getIndex(key);
Node<K,V> cur = nodes[idx];
//如果是空就说明不存在,直接返回null
if (cur == null){
return null;
}
//记录前驱节点,删除的时候需要用
Node<K,V> pre = null;
//如果要删除的节点恰好是头节点,特殊处理
if (cur.key == key){
nodes[idx] = cur.next;
return key;
}
//寻找要删除的目标节点在链表中,寻找要删除的节点
while (cur != null){
if (cur.key == key){
pre.next = cur.next;
return key;
}
pre = cur;
cur = cur.next;
}
return null;
}
private int getIndex(K key) {
int hash = Integer.hashCode((Integer) key);
hash ^= (hash >>> 16);
return hash % CAPACITY;
}
}
下面进行测试
public class Main {
public static void main(String[] args) {
// Map<Integer, Integer> hashMap = new HashMap<>();
MyHashMap<Integer, Integer> hashMap = new MyHashMap<>();
hashMap.put(1,1);
hashMap.put(2,2);
hashMap.put(1,9);
hashMap.put(3,3);
System.out.println(hashMap.get(1));
System.out.println(hashMap.get(2));
System.out.println(hashMap.get(3));
System.out.println("-------------");
System.out.println(hashMap.remove(10));
System.out.println(hashMap.remove(1));
System.out.println(hashMap.get(1));
}
}
附上结果