顯示 Java 中的 HashMap 元素
建立一個 HashMap −
HashMap hm = new HashMap();
向隨後要顯示的 HashMap 中新增元素 −
hm.put("Maths", new Integer(98));
hm.put("Science", new Integer(90));
hm.put("English", new Integer(97));
hm.put("Physics", new Integer(91));現在,要顯示 HashMap 元素,請使用迭代器。以下是顯示 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();
System.out.println("Elements: "+hm);
}
}輸出
Maths: 98
English: 97
Chemistry: 93
Science: 90
Physics: 91
Elements: {Maths=98, English=97, Chemistry=93, Science=90, Physics=91}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP