访问Map#entrySet()时出现“不兼容的类型”

Fun*_*uit 5 java intellij-idea

我正在研究一个简单的配置文件阅读器,但很有趣,但是在编写测​​试方法时遇到了一个奇怪的错误。在其中是一个for循环,并且我已确保它会引起问题。它给了我这个编译错误:

Incompatible types:
    Required: java.util.Map.Entry
    Found: java.lang.Object
Run Code Online (Sandbox Code Playgroud)

Map声明是这样的:

Map<String, String> props = new HashMap<String, String>();
Run Code Online (Sandbox Code Playgroud)

for循环如下所示:

for (Map.Entry<String, String> entry : props.entrySet()) {
    //Body
}
Run Code Online (Sandbox Code Playgroud)

没有导入的SSCCE证明了这个问题(至少在IntelliJ中):

public class A {
    public static void main(String[] args) {
        Map<String, String> props = new HashMap<String, String>();
        for (int i = 0; i < 100; i++) {
            props.put(new BigInteger(130, random).toString(32), new BigInteger(130, random).toString(32));
        }
        for (Map.Entry<String, String> entry : props.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

mapMap<String, String>,所以这不是问题。我已经用谷歌搜索了替代方法,但是人们使用的主要方法似乎就是这种方法!但是由于某种原因,它仍然失败。任何帮助,将不胜感激。如果您提供替代解决方案,请确保它是快速的-这些配置文件可能很大。

Old*_*eon 5

这是您可能正在做的事情的演示-如果没有更多代码,很难确定。

class ATest<T> {
  Map<String, String> props = new HashMap<String, String>();

  void aTest() {
    // Works fine.
    for (Map.Entry<String, String> entry : props.entrySet()) {
    }
  }

  void bTest() {
    ATest aTest = new ATest();
    // ERROR! incompatible types: Object cannot be converted to Entry<String,String>
    for (Map.Entry<String, String> entry : aTest.props.entrySet()) {
    }
  }

  void cTest(Map props) {
    // ERROR! incompatible types: Object cannot be converted to Entry<String,String>
    for (Map.Entry<String, String> entry : props.entrySet()) {
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

请注意,在中,bTest我创建了一个ATest不带泛型类型参数的对象。在这种情况下,Java 将从类中删除所有通用信息,包括从类中<String,String>props变量中删除的信息。

或者-您可能无意中删除了属性映射的通用性质,如我在中演示的cTest