13/13 Help me understand what I did



for (String city : majorCities.keySet()) {
    System.out.println(city + " was founded in " + majorCities.get(city));

I need help understanding WHY this prints out the different values when calling the same variable. In "System.out.println(city + " was founded in " + majorCities.get(city)" the first time you call "city" it returns the string, and the second time you call it, it returns the integer. Why is that?


Right after your FOR-loop add following code lines....

System.out.println( majorCities.keySet());

and you will see that the keySet() Method gives you an Array
[New York, London, Sao Paulo, Mexico City]
of key's
and with
for (String city : majorCities.keySet())
you will iterate over the Array
and at each iteration the city variable will contain 1 of the key's

iteration-1 city = "New York"
iteration-2 city = "London"
iteration-3 city = "Sao Paulo"
iteration-4 city = "Mexico City"

Now if you use the get() Method
in the 1st iteration ( city variable being "New York" )
you =get= the associated-Value of the "New York" key.



This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.