Java compilation error in this HashMap. Why is the compiler catching an Object being converted into a String?

  1. vehicles.keySet() returns a collection of Object, not String. Just because you put strings in as the keys, the API doesn’t change.
    One approach would be:

    for(Object keyObj: vehicles.keySet())
    {
    String key = keyObj.toString(); // or cast to (String)

  2. Same issue – get() returns an Object. Just because you used a string, the API is still just an object. Again either cast or use toString.

As has been hinted in various comments, if you use generics the compiler has a much better idea of “what types are where”. If you define your map like Map<String,String> mapA = new HashMap<String, String>(); then your original code may work because the compiler knows what the data types in the map are.

Leave a Comment