向 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP