我正在尝试迭代现有的 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!
}
}
}
请使用
System.out.println(pair.getKey() + " = " + pair.getValue());
来代替。
map
是 HashMap
,而 pair
是具有键和值属性的相关 Entry
。