在下面的简短代码片段中,Eclipse 标记了有关 String key = pair.getKey();
和 String value = pair.getValue();
的错误声明,说
"Type mismatch: cannot convert from Object to String"
这是相关代码:
for (Map<String, String> dic : dics) {
Iterator it = dic.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
String key = pair.getKey();
String value = pair.getValue();
}
}
这是为什么?
到目前为止我看到的所有示例都没有将 pair.getKey() 或 pair.getValue() 转换为 String,因此我想在继续解决方案之前了解发生了什么。
最佳答案
试试这个:
for (Map<String, String> dic : dics) {
Iterator<Map.Entry<String, String>> it = dic.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pair = it.next();
String key = pair.getKey();
String value = pair.getValue();
}
}
甚至更好(内部工作是相同的,但不那么冗长):
for (Map<String, String> dic : dics) {
for(Map.Entry<String, String> pair : dic.entrySet()){
String key = pair.getKey();
String value = pair.getValue();
}
}
关于java - 为什么 Map<String, String> 的键(或值)没有作为字符串返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5392396/