Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 237
Javed Solkar Avatar asked Mar 16 '23 10:03

Javed Solkar


1 Answers

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) {

}
like image 150
Eran Avatar answered Mar 28 '23 23:03

Eran