我正在字典中插入记录,同时检索我使用的代码如下:
System.out.println(newLine + "Items in the dictionary..." + dict + newLine);
,它给我的结果是:
Items in the dictionary...{pa=1234567890, abcd=8976543245}
但我想以不同的方式。我想分别访问每个记录和字段。我想要这样的结果:
Name Contact
pa 1234567890
abcd 8976543245
Dictionary
有keys
方法来获取键,您可以遍历它们并获取值
Enumeration<String> e = dictionary.keys();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
如果是自定义集合,你可以写自己的Iterator
如果是Map
或HashTable
你可以使用
遍历字典例子 for (Entry<String, String> entry : dict.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
for (String key : dict.keySet()) {
System.out.println(key + " " + dict.get(key));
}
在Java8 dict.forEach((k, v) -> System.out.println(k + " " + v));
Dictionary
有keys
方法来获取键,你可以遍历它并获取值
编辑
将声明更改为
Hashtable<String, String> dict = new Hashtable<String, String>();
这样你就可以得到遍历HashTable
的方法
您可以使用for循环遍历dict.keys()
,然后使用dict.get()
检索每个键的值。