我写了下面的代码来检索 HashMap 中的值。但它没有用。
HashMap<String, String> facilities = new HashMap<String, String>();
Iterator i = facilities.entrySet().iterator();
while(i.hasNext())
{
String key = i.next().toString();
String value = i.next().toString();
System.out.println(key + " " + value);
}
我修改了代码以包含 SET 类并且它工作正常。
Set s= facilities.entrySet();
Iterator it = facilities.entrySet().iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
谁能指导我在没有 SET 类的情况下上面的代码出了什么问题??
P.S - 我没有太多编程经验,最近开始使用 java
最佳答案
您正在调用 next()
两次。
试试这个:
while(i.hasNext())
{
Entry e = i.next();
String key = e.getKey();
String value = e.getValue();
System.out.println(key + " " + value);
}
简而言之,您还可以使用以下代码(它还保留了类型信息)。使用 Iterator
是 Java-1.5 之前的风格。
for(Entry<String, String> entry : facilities.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " " + value);
}
关于java - 在 Java 中检索 HashMap 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15022149/