向 HashMap 中新增元素


要向 HashMap 中新增元素,請使用 put() 方法。

首先,建立一個 HashMap −

HashMap hm = new HashMap();

現在,讓我們向 HashMap 中新增一些元素 −

hm.put("Maths", new Integer(98));
hm.put("Science", new Integer(90));
hm.put("English", new Integer(97));

以下是一個向 HashMap 中新增元素的示例 −

示例

 線上示例

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Maths", new Integer(98));
      hm.put("Science", new Integer(90));
      hm.put("English", new Integer(97));
      hm.put("Physics", new Integer(91));
      hm.put("Chemistry", new Integer(93));
      // Get a set of the entries
      Set set = hm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
   }
}

輸出

Maths: 98
English: 97
Chemistry: 93
Science: 90
Physics: 91

更新於: 30-Jul-2019

6K+ 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.