1

I tried to use for each loop to iterate through HashMap keys but it doesn't compile.

Here is my code:

import java.util.Map;
import java.util.HashMap;

public class theseeker{
    public static void main(String[] args){

        Map blue = new HashMap<Character,Integer>();
        for(char c = 'a';c <= 'z';c++)
            blue.put(new Character(c),new Integer((int)c));

        for(Character c : blue.keySet())
            System.out.println(c);


    }


}

I get this error:

 Object cannot be converted to Character
        for(Character c : blue.keySet())
                                     ^

Does it happen beacuse of using interface?

1 Answers1

2

You're map defaults to objects set it's casts

Map<Character, Integer> blue = new HashMap<>();

After cleaning up your code it should look like the following

public static void main(String[] args) {
    Map<Character, Integer> blue = new HashMap<>();

    for (char c = 'a'; c <= 'z'; c++) {
        blue.put(c, (int) c);
    }

    for (Character c : blue.keySet()) {
        System.out.println(c);
    }
}
SamHoque
  • 2,978
  • 2
  • 13
  • 43