public class MyHashMap<K,V> {
private static final int DEFAULT_CAPTIY=16;
private static final float DEFAULT_FACOTR=0.75f;
private float loadFactor = 0;
private int initCapacity = 0;
private Node[] table=null;
public MyHashMap(){
this.loadFactor=DEFAULT_FACOTR;
this.initCapacity=DEFAULT_CAPTIY;
table=new Node[this.initCapacity];
}
public MyHashMap(int initCapacity, float loadFactor){
this.loadFactor = loadFactor;
this.initCapacity = initCapacity;
table = new Node[this.initCapacity];
}
private int hash(K key){
int h;
return (key == null) ? 0 : Math.abs((h = key.hashCode())) ^ (h >>> 16);
}
public V put(K key, V value) {
// 确定index
int index = hash(key) % initCapacity;
if (table[index] != null) {
Node<K, V> e = table[index];
Node<K, V> e2 = null;
while (e != null) {
if (hash(e.key) == hash(key) && e.key.equals(key)) {
// 如果键相同,则更新值
e.value = value;
}
// 遍历链表判断是否已经存在相同的key
e2 = e;
e = e.next;
}
// 如果不存在相同的key,则直接插到尾结点的后面
e2.next = new Node<>(key, value, null, index);
} else {
// 如果table[index]处为空,则直接插入
Node<K, V> e = new Node<>(key, value, null, index);
table[index] = e;
}
return value;
}
public V get(K k){
int keyHash=hash(k)%initCapacity;
Node<K,V> e=table[keyHash];
if(e==null)
return null;
while (e!=null){
if(hash(e.key) == hash(k) && e.key.equals(k))
return V;
e=e.next;
}
return null;
}
}
class Node<K,V> {
public int hash;
public K key;
public V value;
public Node next;
public Node(K k,V v,Node next, int hash){
this.key=k;
this.value=v;
this.next=next;
this.hash=hash;
}
}
评论区