I gave the Map as a parameter for print Method and printing logic was implemented inside method.
But when i tried to iterate using simple "for loop" as below
--------------------------------------------------------------------------------------------------------
public static void printMapWithEntrySet(Map nameCount) {
for (Entry
String key = entry.getKey().toString();
Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
}
---------------------------------------------------------------------------------------------------------
there was a Type mismatch error
( "Type mismatch: cannot convert from element type Object to Map.Entry
showing in the highlighted line.
for (Entry
I found the reason, it was very simple mistake. error is in the parameter.
I have not included type in Map definition the parameter.
It should be
Map
So the correct formation of the method would be
----------------------------------------------------------------------------------------------------------
public static void printMapWithEntrySet(Map
for (Entry
String key = entry.getKey().toString();
Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
}
----------------------------------------------------------------------------------------------------------
Because of that, Entry set object cannot cast the value for Entry and it comes as Object as stated below
----------------------------------------------------------------------------------------------------------
public static void printMapWithEntrySet(Map nameCount) {
for (Object entry : nameCount.entrySet()) {
}
}
----------------------------------------------------------------------------------------------------------
Without the type definition of the Map , that is "
So the code will looks like below.
----------------------------------------------------------------------------------------------------------
public static void printMap(Map nameCount) {
Iterator
while (it.hasNext()) {
Entry
System.out.println("key, " + pairs.getKey() + " value "
+ pairs.getValue());
}
}
----------------------------------------------------------------------------------------------------------
Here we have to use an Iterator. That is an additional burden.
No comments:
Post a Comment