0

I copied this code LITERALLY from this website: https://www.w3schools.com/java/showjava.asp?filename=demo_hashmap_loop_key

But it still gives an error as mentioned above referring to: 'for (String i : capitalCities.keySet())!'

Somebody knows how to correct this mistake??


import java.util.HashMap;

public class MyClass {
  public static void main(String[] args) {
    HashMap capitalCities = new HashMap();
    capitalCities.put("England", "London");
    capitalCities.put("Germany", "Berlin");
    capitalCities.put("Norway", "Oslo");
    capitalCities.put("USA", "Washington DC");

    for (String i : capitalCities.keySet()) {
      System.out.println(i);
    }
  }
}

  • 3
    Use `HashMap capitalCities = new HashMap<>();`. – Slaw Oct 17 '19 at 09:55
  • That's right Mr. Slaw Thanks!! Amazing that such a mistake is made on a Java tutorial site, isn't it? –  Oct 17 '19 at 09:59
  • I think it's a rendering issue. If you look at the page source you'll see it uses the parameterized types, it just isn't showing the `<...>` likely due to some issue with the HTML being used. Also, check out [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/) if you want to know a little more about parameterized types versus raw types. – Slaw Oct 17 '19 at 10:11
  • It's a rendering issue. view-source:https://www.w3schools.com/java/showjava.asp?filename=demo_hashmap_loop_key in Firefox shows that the actual line is `HashMap capitalCities = new HashMap();`. – MC Emperor Oct 17 '19 at 12:53

1 Answers1

2

Your program will throw the below compilation error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Type mismatch: cannot convert from element type Object to String

From your code, capitalCities.keySet() will return Set of generic type. So, in order to return the String Set, either we can use one of the below solution.

Solution 1: for (Object i : capitalCities.keySet()) Changing the data type of 'i' as generic Object.

Solution 2: HashMap<String, String> capitalCities = new HashMap<String, String>(); We can define datatype for the key and the value of the map as String.

Note: For code readability, it is recommended to use "Solution 2".

  • Note that `keySet()` returns a `Set` (or a `Set` when using raw types), not an array. – Slaw Oct 17 '19 at 10:45