Java设计哈希映射的方法
更新时间:2025年05月15日 14:40:54 作者:真真最可爱
这篇文章主要介绍了Java设计哈希映射的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
设计哈希映射


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);
*/到此这篇关于Java设计哈希映射的方法的文章就介绍到这了,更多相关java哈希映射内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
@RequestParam 和@RequestBody注解的区别解析
在 Spring MVC 中,我们可以使用 @RequestParam 和 @RequestBody 来获取请求参数,但它们在用法和作用上有一些区别,这篇文章主要介绍了@RequestParam 和@RequestBody注解的区别,需要的朋友可以参考下2023-06-06


最新评论