我见过的每个Java Map迭代示例都推荐这种范例:
for (Map.Entry<String, String> item : hashMap.entrySet()) {
String key = item.getKey();
String value = item.getValue();
}
然而,当我尝试这样做时,我从编译器得到一个警告:
Incompatible types: java.lang.Object cannot be converted to java.util.Map.Entry<java.lang.String, java.lang.Object>
下面是我的代码——我看到的唯一的问题是我在一个Map对象数组上迭代,然后在单个Map的元素上迭代:
result = getArrayOfMaps();
// Force to List LinkedHashMap
List<LinkedHashMap> result2 = new ArrayList<LinkedHashMap>();
for (Map m : result) {
LinkedHashMap<String, Object> n = new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : m.entrySet()) {
n.put(entry.getKey(),entry.getValue());
}
result2.add(n);
}
我错过了什么明显的东西吗?
发生这种情况是因为您使用的是原始类型:List<LinkedHashMap>
而不是List<LinkedHashMap<Something, SomethingElse>>
。因此,entrySet
只是Set
而不是Set<Map.Entry<Something, SomethingElse>>
。别那样做。