日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

HashMap如何在Java中工作

發布時間:2023/12/3 java 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HashMap如何在Java中工作 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

面試中最常見的問題是“ HashMap如何在Java中工作”,“ HashMap的獲取和放置方法如何在內部工作”。 在這里,我試圖通過一個簡單的示例來解釋內部功能。 而不是理論,我們將首先從示例開始,以便您更好地理解,然后我們將了解get和put函數在Java中的工作方式。
讓我們舉一個非常簡單的例子。 我有一個Country類,我們將使用Country類對象作為鍵,并使用其大寫名稱(字符串)作為值。 下面的示例將幫助您了解如何將這些鍵值對存儲在哈希圖中。

1. Country.java

package org.arpit.javapostsforlearning; public class Country {String name;long population;public Country(String name, long population) {super();this.name = name;this.population = population;}public String getName() {return name;}public void setName(String name) {this.name = name;}public long getPopulation() {return population;}public void setPopulation(long population) {this.population = population;}// If length of name in country object is even then return 31(any random number) and if odd then return 95(any random number).// This is not a good practice to generate hashcode as below method but I am doing so to give better and easy understanding of hashmap.@Overridepublic int hashCode() {if(this.name.length()%2==0)return 31;else return 95;}@Overridepublic boolean equals(Object obj) {Country other = (Country) obj;if (name.equalsIgnoreCase((other.name)))return true;return false;}}

如果您想了解有關對象的哈希碼和equals方法的更多信息,可以在Java中引用hashcode()和equals()方法。

2. HashMapStructure.java(主類)

import java.util.HashMap; import java.util.Iterator;public class HashMapStructure {/*** @author Arpit Mandliya*/public static void main(String[] args) {Country india=new Country("India",1000);Country japan=new Country("Japan",10000);Country france=new Country("France",2000);Country russia=new Country("Russia",20000);HashMap<country,string> countryCapitalMap=new HashMap<country,string>();countryCapitalMap.put(india,"Delhi");countryCapitalMap.put(japan,"Tokyo");countryCapitalMap.put(france,"Paris");countryCapitalMap.put(russia,"Moscow");Iterator<country> countryCapitalIter=countryCapitalMap.keySet().iterator();//put debug point at this linewhile(countryCapitalIter.hasNext()){Country countryObj=countryCapitalIter.next();String capital=countryCapitalMap.get(countryObj);System.out.println(countryObj.getName()+"----"+capital);}}} </country></country,string></country,string>

現在,在第23行放置調試點,然后右鍵單擊project-> debug as-> java應用程序。 程序將在第23行停止執行,然后右鍵單擊countryCapitalMap,然后選擇watch。您將看到如下結構。
現在,從上圖可以觀察到以下幾點

  • 有一個名為table的Entry []數組,其大小為16。
  • 該表存儲Entry類的對象。 HashMap類具有一個稱為Entry的內部類。此Entry具有鍵值作為實例變量。 讓我們看一下輸入類Entry Structure的結構。
  • static class Entry implements Map.Entry {final K key;V value;Entry next;final int hash;...//More code goes here }
  • 每當我們嘗試將任何鍵值對放入哈希圖中時,都會為鍵值實例化Entry類對象,并且該對象將存儲在上述Entry [](表)中。 現在,您一定想知道,上面創建的Enrty對象將存儲在哪里(表中的確切位置)。 答案是,通過調用Hascode()方法為密鑰計算哈希碼。 該哈希碼用于計算上述Entry []表的索引。
  • 現在,如果您在上圖中的數組索引10處看到,它就有一個名為HashMap $ Entry的Entry對象。
  • 我們在hashmap中放置了4個鍵值,但似乎只有2個!!!!!這是因為,如果兩個對象具有相同的哈希碼,則它們將存儲在相同的索引處。 現在的問題如何產生? 它以LinkedList的形式存儲對象(邏輯上)。
  • 那么如何計算上述國家/地區鍵值對的哈希碼。

    Hashcode for Japan = 95 as its length is odd. Hashcode for India =95 as its length is odd HashCode for Russia=31 as its length is even. HashCode for France=31 as its length is even.

    下圖將清楚地說明LinkedList概念。
    因此,現在,如果您對哈希圖的結構有了很好的了解,那么讓我們通過put和get方法。

    放置:

    讓我們看一下put方法的實現:

    /*** Associates the specified value with the specified key in this map. If the* map previously contained a mapping for the key, the old value is* replaced.** @param key* key with which the specified value is to be associated* @param value* value to be associated with the specified key* @return the previous value associated with <tt>key</tt>, or <tt>null</tt>* if there was no mapping for <tt>key</tt>. (A <tt>null</tt> return* can also indicate that the map previously associated* <tt>null</tt> with <tt>key</tt>.)*/public V put(K key, V value) {if (key == null)return putForNullKey(value);int hash = hash(key.hashCode());int i = indexFor(hash, table.length);for (Entry<k , V> e = table[i]; e != null; e = e.next) {Object k;if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {V oldValue = e.value;e.value = value;e.recordAccess(this);return oldValue;}}modCount++;addEntry(hash, key, value, i);return null;}

    現在讓我們逐步了解上面的代碼

  • 檢查鍵對象是否為空。 如果key為null,則它將存儲在table [0]中,因為null的哈希碼始終為0。
  • 調用關鍵對象的hashcode()方法并計算哈希碼。 該哈希碼用于查找用于存儲Entry對象的數組的索引。 有時可能發生的是,這個哈希碼功能寫得不好所以JDK設計師已經把另一個函數調用的散列(),接受作為argument.If您想了解更多關于散列()函數上面計算哈希值,你可以參考散列和indexFor hashmap中的方法 。
  • indexFor(hash,table.length)用于計算表數組中的確切索引,以存儲Entry對象。
  • 正如我們在示例中看到的那樣,如果兩個關鍵對象具有相同的哈希碼(稱為沖突 ),則它將以鏈表的形式存儲。因此在這里,我們將遍歷鏈表。
    • 如果我們剛剛計算出的那個索引上沒有元素,那么它將直接把Entry對象放在那個索引上。
    • 如果該索引處存在元素,則它將迭代直到獲得Entry-> next作為null。然后當前的Entry對象成為該鏈表中的下一個節點
    • 如果我們再次放置相同的鍵,從邏輯上講應該替換舊值該怎么辦。 是的,它會這樣做。在迭代時,將通過調用equals()方法( key.equals(k) )檢查鍵是否相等,如果此方法返回true,則它將值對象替換為當前Entry的值對象。

    得到:

    讓我們看一下get的實現:

    /*** Returns the value to which the specified key is mapped, or {@code null}* if this map contains no mapping for the key.** <p>* More formally, if this map contains a mapping from a key {@code k} to a* value {@code v} such that {@code (key==null ? k==null :* key.equals(k))}, then this method returns {@code v}; otherwise it returns* {@code null}. (There can be at most one such mapping.)** </p><p>* A return value of {@code null} does not <i>necessarily</i> indicate that* the map contains no mapping for the key; it's also possible that the map* explicitly maps the key to {@code null}. The {@link #containsKey* containsKey} operation may be used to distinguish these two cases.** @see #put(Object, Object)*/public V get(Object key) {if (key == null)return getForNullKey();int hash = hash(key.hashCode());for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {Object k;if (e.hash == hash && ((k = e.key) == key || key.equals(k)))return e.value;}return null;}

    當您了解了hashmap的put功能時。 因此,了解獲取功能非常簡單。 如果傳遞任何鍵以從哈希圖獲取值對象。

  • 檢查鍵對象是否為空。 如果key為null,則將返回Object的值位于table [0]。
  • 調用關鍵對象的hashcode()方法并計算哈希碼。
  • indexFor(hash,table.length)用于使用生成的哈希碼獲取Entry對象來計算表數組中的精確索引。
  • 在表數組中獲取索引后,它將遍歷鏈表并通過調用equals()方法檢查鍵是否相等,如果返回true,則返回Entry對象的值,否則返回null。
  • 記住要點:

    • HashMap具有一個稱為Entry的內部類,該類存儲鍵值對。
    • 上面的Entry對象存儲在稱為table的Entry [](Array)中
    • 表的索引在邏輯上稱為存儲桶,它存儲鏈表的第一個元素
    • 關鍵對象的hashcode()用于查找該Entry對象的存儲桶。
    • 如果兩個鍵對象具有相同的哈希碼,則它們將進入表數組的同一存儲桶中。
    • 關鍵對象的equals()方法用于確保關鍵對象的唯一性。
    • 完全不使用值對象的equals()和hashcode()方法

    參考:來自JCG合作伙伴 Arpit Mandliya的HashMap如何在Java中工作 ,有關Java框架和初學者博客的設計模式 。

    翻譯自: https://www.javacodegeeks.com/2014/03/how-hashmap-works-in-java.html

    總結

    以上是生活随笔為你收集整理的HashMap如何在Java中工作的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。