要创建HashMap,请使用HashMap映射和新的-
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[]) { //创建一个哈希映射 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)); //获取一组条目 Set set = hm.entrySet(); //获取一个迭代器 Iterator i = set.iterator(); //显示元素 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