更新時間:2021-10-22 10:23:17 來源:動力節點 瀏覽960次
HashMap 是一個基于 Map 的集合類,用于存儲 Key & value 對,表示為 HashMap<Key, Value> 或 HashMap<K, V>。此類不保證地圖的順序。它類似于 Hashtable 類,除了它是不同步的并且允許空值(空值和空鍵)。
它不是一個有序集合,這意味著它不會以它們插入 HashMap 的相同順序返回鍵和值。它不會對存儲的鍵和值進行排序。您必須需要導入java.util.HashMap或其超類才能使用 HashMap 類和方法。
在這個例子中,我們已經演示了 HashMap 類的幾乎所有重要方法。
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {
public static void main(String args[]) {
/* This is how to declare HashMap */
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
/*Adding elements to HashMap*/
hmap.put(12, "Chaitanya");
hmap.put(2, "Rahul");
hmap.put(7, "Singh");
hmap.put(49, "Ajeet");
hmap.put(3, "Anuj");
/* Display content using Iterator*/
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
System.out.println(mentry.getValue());
}
/* Get values based on key*/
String var= hmap.get(2);
System.out.println("Value at index 2 is: "+var);
/* Remove values based on key*/
hmap.remove(3);
System.out.println("Map key and values after removal:");
Set set2 = hmap.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry mentry2 = (Map.Entry)iterator2.next();
System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
System.out.println(mentry2.getValue());
}
}
}
輸出:
key is: 49 & Value is: Ajeet
key is: 2 & Value is: Rahul
key is: 3 & Value is: Anuj
key is: 7 & Value is: Singh
key is: 12 & Value is: Chaitanya
Value at index 2 is: Rahul
Map key and values after removal:
Key is: 49 & Value is: Ajeet
Key is: 2 & Value is: Rahul
Key is: 7 & Value is: Singh
Key is: 12 & Value is: Chaitanya
如果您想了解更多關于HashMap的知識,不妨來關注一下動力節點的Java基礎教程,里面有更多相關內容可以學習,課程通俗易懂,適合小白,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習