for (String str : m.keySet()) {//this works fine }
Set set = m.keySet(); for (String str : set) {//Type mismatch: cannot convert from element type Object to String }
Both do the same thing as iterating over the (String) keys of the Set object than why I get the error in the second code.
You cannot use the raw type Set, since in this case the elements Setwill be considered a type Object.
Set
Object
Instead, specify the type of elements Set:
Set<String> set = m.keySet(); for (String str : set) { }
This is because Set does not know which type will be used, therefore, to throw an exception, you should use it Stringas a general feed for it. as below fragment
String
Set<String> set = m.keySet();