Reputation: 10662
In the following short code snippet, Eclipse flags an error about the String key = pair.getKey();
and the 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.
Upvotes: 1
Views: 3727
Reputation: 298978
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();
}
}
Upvotes: 11
Reputation: 24791
Basically the idea is that your iterator(it) and entry(pair) should also be generics-ized.
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();
}
Upvotes: 1
Reputation: 88707
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();
}
}
Upvotes: 1
Reputation: 17888
You have the Entry
as a raw unparametrized type type.
Use Entry<String, String>
instead of the raw Entry
.
Upvotes: 0
Reputation: 533560
You have not carried the types through the it
or 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();
}
}
Upvotes: 8