[英]Why is key (or value) of Map<String, String> not returned as String?
In the following short code snippet, Eclipse flags an error about the String key = pair.getKey();
在下面的简短代码片段中,Eclipse标记了有关
String key = pair.getKey();
的错误String key = pair.getKey();
and the String value = pair.getValue();
和
String value = pair.getValue();
statements, saying that 声明,说
"Type mismatch: cannot convert from Object to String"
“类型不匹配:无法从对象转换为字符串”
This is the relevant code: 这是相关代码:
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();
}
}
Why is that? 这是为什么?
All examples I have seen so far, do not cast pair.getKey() or pair.getValue() to String, so I would like to understand what's happening before proceeding with a solution. 到目前为止,我所看到的所有示例都不要将pair.getKey()或pair.getValue()强制转换为String,所以我想在继续解决方案之前先了解发生了什么。
Try this: 尝试这个:
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();
}
}
Or even better (internal working is identical, but this is less verbose): 甚至更好(内部工作是相同的,但这不那么冗长):
for (Map<String, String> dic : dics) {
for(Map.Entry<String, String> pair : dic.entrySet()){
String key = pair.getKey();
String value = pair.getValue();
}
}
You have not carried the types through the it
or pair
您尚未通过
it
或pair
携带类型
Try this 尝试这个
for (Map<String, String> dic : dics) {
for (Map.Entry<String, String> pair : dic.entrySet()) {
String key = pair.getKey();
String value = pair.getValue();
}
}
Try this: 尝试这个:
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();
}
} }
Basically the idea is that your iterator(it) and entry(pair) should also be generics-ized. 基本上,这个想法是您的迭代器(it)和入口(对)也应该是泛型的。
Iterator<Entry<String, String>> it = dic.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> pair = it.next();
String key = pair.getKey();
String value = pair.getValue();
}
You have the Entry
as a raw unparametrized type type. 您具有
Entry
作为原始未参数化的类型类型。
Use Entry<String, String>
instead of the raw Entry
. 使用
Entry<String, String>
代替原始Entry
。
您的Map.Entry声明未按类型参数化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.