Java設(shè)計哈希映射的方法
更新時間:2025年05月15日 14:40:54 作者:真真最可愛
這篇文章主要介紹了Java設(shè)計哈希映射的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
設(shè)計哈希映射


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];
//只要頭節(jié)點不為空,就一種找下去
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];
//創(chuàng)建兩個臨時變量,如果只有一個臨時變量,則最后不能給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);
*/到此這篇關(guān)于Java設(shè)計哈希映射的方法的文章就介紹到這了,更多相關(guān)java哈希映射內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
@RequestParam?和@RequestBody注解的區(qū)別解析
在 Spring MVC 中,我們可以使用 @RequestParam 和 @RequestBody 來獲取請求參數(shù),但它們在用法和作用上有一些區(qū)別,這篇文章主要介紹了@RequestParam?和@RequestBody注解的區(qū)別,需要的朋友可以參考下2023-06-06
springboot打包部署到linux服務(wù)器的方法
這篇文章主要介紹了springboot打包部署到linux服務(wù)器的方法,通過實例代碼相結(jié)合的形式給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06
Java編程實現(xiàn)深度優(yōu)先遍歷與連通分量代碼示例
這篇文章主要介紹了Java編程實現(xiàn)深度優(yōu)先遍歷與連通分量代碼示例,2017-11-11

