在下面的简短代码片段中,Eclipse标记了有关语句String key = pair.getKey();和String value = pair.getValue();语句的错误,并说明了这一点
"类型不匹配:无法从Object转换为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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是为什么?
到目前为止我看到的所有示例都没有将pair.getKey()或pair.getValue()强制转换为String,所以我想在继续解决之前了解发生了什么.
Sea*_*oyd 11
试试这个:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
甚至更好(内部工作是相同的,但这不那么冗长):
for (Map<String, String> dic : dics) {
for(Map.Entry<String, String> pair : dic.entrySet()){
String key = pair.getKey();
String value = pair.getValue();
}
}
Run Code Online (Sandbox Code Playgroud)
你没有通过it或携带类型pair
试试这个
for (Map<String, String> dic : dics) {
for (Map.Entry<String, String> pair : dic.entrySet()) {
String key = pair.getKey();
String value = pair.getValue();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3252 次 |
| 最近记录: |