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。您將看到如下結構。
現在,從上圖可以觀察到以下幾點
那么如何計算上述國家/地區鍵值對的哈希碼。
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;}現在讓我們逐步了解上面的代碼
- 如果我們剛剛計算出的那個索引上沒有元素,那么它將直接把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功能時。 因此,了解獲取功能非常簡單。 如果傳遞任何鍵以從哈希圖獲取值對象。
記住要點:
- HashMap具有一個稱為Entry的內部類,該類存儲鍵值對。
- 上面的Entry對象存儲在稱為table的Entry [](Array)中
- 表的索引在邏輯上稱為存儲桶,它存儲鏈表的第一個元素
- 關鍵對象的hashcode()用于查找該Entry對象的存儲桶。
- 如果兩個鍵對象具有相同的哈希碼,則它們將進入表數組的同一存儲桶中。
- 關鍵對象的equals()方法用于確保關鍵對象的唯一性。
- 完全不使用值對象的equals()和hashcode()方法
翻譯自: https://www.javacodegeeks.com/2014/03/how-hashmap-works-in-java.html
總結
以上是生活随笔為你收集整理的HashMap如何在Java中工作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小米电脑系统自带软件(小米的电脑软件)
- 下一篇: 150个Java面试问答-最终清单(PD