共計 715 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
在 Java 中,HashMap 是一種常用的數(shù)據(jù)結(jié)構(gòu),用于存儲鍵值對。以下是使用 HashMap 的一些基本操作:
- 創(chuàng)建一個 HashMap 對象:
HashMap<String, Integer> map = new HashMap<>();
- 添加鍵值對到 HashMap 中:
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
- 從 HashMap 中獲取值:
int value = map.get("key1");
System.out.println(value); // 輸出:1
- 檢查 HashMap 中是否包含某個鍵:
boolean containsKey = map.containsKey("key2");
System.out.println(containsKey); // 輸出:true
- 遍歷 HashMap 中的所有鍵值對:
for (Map.Entry<String, Integer> entry : map.entrySet()) {String key = entry.getKey();
int value = entry.getValue();
System.out.println(key + " : " + value);
}
- 刪除 HashMap 中的某個鍵值對:
map.remove("key3");
- 獲取 HashMap 中的鍵集合和值集合:
Set<String> keySet = map.keySet();
Collection<Integer> values = map.values();
這些是 HashMap 的一些基本用法,可以根據(jù)具體需要進(jìn)行相應(yīng)的操作和擴(kuò)展。HashMap 還有很多其他方法和功能,可以查閱官方文檔進(jìn)行了解。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完