Search code examples
javadictionarycollectionsiterator

Iterating 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 are doing same thing i.e iterating over Keys(String) of Set object than why i am getting error in second code.


Solution

  • You shouldn't use the raw Set type, since in that case the elements of the Set would be assumed to be of Object type.

    Instead, specify the type of elements the Set holds :

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