设计Hash映射
原创
©著作权归作者所有:来自51CTO博客作者wx65ea5efedaa98的原创作品,请联系作者获取转载授权,否则将追究法律责任
摘要:该文章展示了一个简单的Java类MyHashMap
,它使用链表解决哈希冲突。类中包含put
、get
和remove
方法,用于存储、检索和删除键值对。每个桶(buckets
)是一个链表,键值对通过键的哈希值定位到对应的链表节点
设计Hash映射
class MyHashMap {
class Node{
int key;
int value;
Node next;
public Node(int key, int value){
this.key= key;
this.value=value;
}
}
private Node [] buckets;
int size;
public MyHashMap() {
size=0;
buckets =new Node[16];
}
public void put(int key, int value) {
//用key直接代表hashcode(),%bucket.length能保证不会溢出
int index = key %buckets.length;
Node head =buckets[index];
//只要头节点不为空,就一种找下去
while(head != null && head.key != key){
head =head.next;
}
//找到相同key
if(head != null ){
head.value=value;
//不存在这个key,用的是头插法
}else{
Node newnode =new Node(key,value);
newnode.next=buckets[index];
buckets[index] =newnode;
size++;
}
}
public int get(int key) {
int index= key % buckets.length;
Node head =buckets[index];
while(head != null && head.key != key){
head=head.next;
}
return head == null ? -1 : head.value;
}
public void remove(int key) {
int index= key % buckets.length;
Node head =buckets[index];
//创建两个临时变量,如果只有一个临时变量,则最后不能给bucket[index]进行赋值
Node dummy= new Node(0,0);
Node cur=dummy;
dummy.next=head;
while(cur.next != null && cur.next.key != key){
cur=cur.next;
}
if(cur.next!=null && cur.next.key == key){
cur.next=cur.next.next;
size--;
}
buckets[index] =dummy.next;
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/