迭代 HashMap 错误(无法解析“HashMap”中的方法)

问题描述 投票:0回答:1

我正在尝试迭代现有的 HashMap,但在循环中调用方法 .getKey 和 .getValue 时,我收到错误:无法解析“HashMap”中的方法“getKey”。我导入了必要的包,正如您在下面的代码中看到的那样。任何建议将不胜感激!

import java.util.HashMap;
import java.util.Map;

public class HashMapExamples {
  public static void main(String[] args) {
   
    HashMap<String,Integer> map = new HashMap<>();
    
    map.put("cloud", 7);
    map.put("taco", 29);
    map.put("sponge", 8);

    for (Map.Entry<String, Integer> pair: map.entrySet()) {
        System.out.println(map.getKey() + " = " + map.getValue()); // this line is error-ing! 
    }
  }
}
java for-loop hashmap maps
1个回答
0
投票

请使用

System.out.println(pair.getKey() + " = " + pair.getValue());
来代替。

map
HashMap
,而
pair
是具有键和值属性的相关
Entry

© www.soinside.com 2019 - 2024. All rights reserved.