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


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能保證不會(huì)溢出
int index = key %buckets.length;
Node head =buckets[index];
//只要頭節(jié)點(diǎn)不為空,就一種找下去
while(head != null && head.key != key){
head =head.next;
}
//找到相同key
if(head != null ){
head.value=value;
//不存在這個(gè)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)建兩個(gè)臨時(shí)變量,如果只有一個(gè)臨時(shí)變量,則最后不能給bucket[index]進(jìn)行賦值
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è)計(jì)哈希映射的方法的文章就介紹到這了,更多相關(guān)java哈希映射內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
@RequestParam?和@RequestBody注解的區(qū)別解析
在 Spring MVC 中,我們可以使用 @RequestParam 和 @RequestBody 來獲取請(qǐng)求參數(shù),但它們?cè)谟梅ê妥饔蒙嫌幸恍﹨^(qū)別,這篇文章主要介紹了@RequestParam?和@RequestBody注解的區(qū)別,需要的朋友可以參考下2023-06-06
IDEA啟動(dòng)tomcat狀態(tài)404的解決
在使用Idea進(jìn)行Java?Web開發(fā)過程中,經(jīng)常會(huì)遇到Tomcat出現(xiàn)404錯(cuò)誤的問題,本文就來介紹了IDEA啟動(dòng)tomcat狀態(tài)404的解決,具有一定的參考價(jià)值,感興趣的可以了解一下2023-10-10
springboot打包部署到linux服務(wù)器的方法
這篇文章主要介紹了springboot打包部署到linux服務(wù)器的方法,通過實(shí)例代碼相結(jié)合的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-06-06
SpringSecurity默認(rèn)登錄頁的使用示例教程
Spring 是非常流行和成功的 Java 應(yīng)用開發(fā)框架,Spring Security 正是 Spring 家族中的成員,Spring Security 基于 Spring 框架,提供了一套 Web 應(yīng)用安全性的完整解決方案,本文給大家介紹SpringSecurity的默認(rèn)登錄頁的使用教程,感興趣的朋友一起看看吧2023-12-12
Java編程實(shí)現(xiàn)深度優(yōu)先遍歷與連通分量代碼示例
這篇文章主要介紹了Java編程實(shí)現(xiàn)深度優(yōu)先遍歷與連通分量代碼示例,2017-11-11
Java實(shí)戰(zhàn)之實(shí)現(xiàn)用戶登錄
這篇文章主要介紹了Java實(shí)戰(zhàn)之實(shí)現(xiàn)用戶登錄,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04

