Iterate using for each

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.

+4
source share
2 answers

You cannot use the raw type Set, since in this case the elements Setwill be considered a type Object.

Instead, specify the type of elements Set:

Set<String> set = m.keySet();
for (String str : set) {

}
+6
source

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

Set<String> set = m.keySet();
+1
source

All Articles