在 Java 中建立 HashMap


要建立 HashMap,請使用 HashMap map 和 new −

HashMap hm = new HashMap();

現在,設定元素 −

hm.put("Finance", new Double(999.87));
hm.put("Operations", new Double(298.64));
hm.put("Marketing", new Double(39.56));

現在使用以下程式碼顯示元素 −

範例

 線上演示

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("Finance", new Double(999.87));
      hm.put("Operations", new Double(298.64));
      hm.put("Marketing", new Double(39.56));
      // 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();
   }
}

輸出

Finance: 999.87
Operations: 298.64
Marketing: 39.56

更新於: 30-Jul-2019

241 瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.