hashmap java
- IT科技
- 關注:2.65W次
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
java的hashmap是什麼?下面就一起了解一下吧~
HashMap是一個散列表,它儲存的內容是鍵值對(key-value)對映,根據鍵的 HashCode 值儲存資料實現了 Map 介面,HashMap的訪問速度很快,最多允許一條記錄的null鍵,不支援執行緒同步。
hashmap新增元素的方法
HashMap 類提供了很多有用的方法,新增鍵值對(key-value)可以使用 put() 方法:
例項
// 引入 HashMap 類 import java.util.HashMap;public class RunoobTest { public static void main(String[] args) { // 建立 HashMap 物件 Sites HashMap<Integer, String> Sites = new HashMap<Integer, String>(); // 新增鍵值對 Sites.put(1, "Google"); Sites.put(2, "Runoob"); Sites.put(3, "Taobao"); Sites.put(4, "Zhihu"); System.out.println(Sites); }}
執行以上程式碼,輸出結果如下:
{1=Google, 2=Runoob, 3=Taobao, 4=Zhihu}
以下例項建立一個字元串(String)型別的 key 和字串(String)型別的 value:
例項
// 引入 HashMap 類 import java.util.HashMap;public class RunoobTest { public static void main(String[] args) { // 建立 HashMap 物件 Sites HashMap<String, String> Sites = new HashMap<String, String>(); // 新增鍵值對 Sites.put("one", "Google"); Sites.put("two", "Runoob"); Sites.put("three", "Taobao"); Sites.put("four", "Zhihu"); System.out.println(Sites); }}
執行以上程式碼,輸出結果如下:
{four=Zhihu, one=Google, two=Runoob, three=Taobao}
- 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/dianzi/4r3ve9.html