我正在字典中插入记录,在检索时我使用如下代码:
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
的方法
关于java - 如何从java中的Dictionary类一次检索一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33273401/