Java HashMap 迭代 Map.Entry<> 与 Entry<>

Java HashMap iteration Map.Entry<> vs Entry<>

我是 Java 的新手,使用 HashMap 在 Mac 上编写 java。
但是我遇到了一个找不到答案的问题

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

public class Test {
    public static void main(String[] args) {
        Map<String, Integer> hm = new HashMap<>();
        hm.put("a", 1);
        hm.put("b", 2);
        for (Entry<String, Integer> en : hm.entrySet()) {  //this line is different
            System.out.print(en.getKey());
            System.out.println(en.getValue());
        }
    }
}

这段代码在 windows 机器上工作正常,但在我的 Mac 上它弹出一个错误表明 "can not find symbol: Entry "

后来我把代码改成了

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

public class Test {
    public static void main(String[] args) {
        Map<String, Integer> hm = new HashMap<>();
        hm.put("a", 1);
        hm.put("b", 2);
        for (Map.Entry<String, Integer> en : hm.entrySet()) {  //this line is different
            System.out.print(en.getKey());
            System.out.println(en.getValue());
        }
    }
}

现在一切正常。

谁能告诉我为什么?
为什么这段代码在别人的电脑上运行正常,但在我的电脑上却不行?

你确定这会在 windows 中编译吗?

我只是把它放在一个名为 "C:\tmp\etc\Test.java" 的文件中,然后这样做...

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Bret>cd \tmp\etc

C:\tmp\etc>javac Test.java
Test.java:9: error: cannot find symbol
    for (Entry<String, Integer> en : hm.entrySet()) {  //this line is different
         ^
  symbol:   class Entry
  location: class Test
1 error

C:\tmp\etc>

你一定是在做其他事情导致了这个...

您提供的代码也无法在 windows 上编译。 不确定您是否正在编译其他内容。 如果您正在使用控制台并尝试编译并且您有相似的文件名,则可能会发生这种情况。

Map.Entry 位于 java.util.Map 包中。 所以,我的建议是

1. 你可以在代码中引入java.util.Map.Entry
或者
2. 使用 Map.Entry 而不仅仅是 Entry,例如:

for (Map.Entry<String, Integer> en : hm.entrySet())

基本上,当您使用 Map.Entry 时,您是在直接引用 class。 Java 的导入语句是纯语法糖。 import 仅在编译时计算,以指示编译器在代码中的何处查找名称。

当您总是指定 classes 的全限定名时,您可能没有任何导入语句。就像这一行根本不需要导入语句:

javax.swing.JButton but = new  javax.swing.JButton();

导入语句将使您的代码更具可读性,如下所示:

import javax.swing.*
JButton but = new JButton();

希望对您有所帮助。