13/13 Help me understand what I did


#1



https://www.codecademy.com/en/courses/learn-java/lessons/data-structures/exercises/generalizations-data-structures


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?


#2

@goudy,
Right after your FOR-loop add following code lines....

System.out.println("===================");
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
like
majorCities.get(city));
in the 1st iteration ( city variable being "New York" )
you =get= the associated-Value of the "New York" key.

Reference
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
https://community.oracle.com/thread/1154981?start=0&tstart=0


#3

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