在java中检索hashmap值

Nei*_*eil 1 java hashmap

我写下面的代码来检索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);
}
Run Code Online (Sandbox Code Playgroud)

我修改了代码以包含SET类,它工作正常.

Set s= facilities.entrySet();
Iterator it = facilities.entrySet().iterator();
while(it.hasNext())
{
    System.out.println(it.next());
}
Run Code Online (Sandbox Code Playgroud)

没有SET类,任何人都可以指导我上面的代码出了什么问题?

PS - 我没有太多编程exp并且最近开始使用java

Kai*_*Kai 11

你打了next()两次电话.

试试这个:

while(i.hasNext())
{
    Entry e = i.next();
    String key = e.getKey();  
    String value = e.getValue();
    System.out.println(key + " " + value);
}
Run Code Online (Sandbox Code Playgroud)

简而言之,您还可以使用以下代码(它还保留类型信息).以Iterator某种方式使用pre-Java-1.5风格.

for(Entry<String, String> entry : facilities.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key + " " + value);
}
Run Code Online (Sandbox Code Playgroud)