HashMaps and their associated Strings


#1

How does HashMaps Associate the declartion of string "food" with the String within itself? is this because of the : that declares that String food is within restaurantMenu and the computer automatically associates the String food with "Turkey Burger", "Naan Pizza" etc because these are the only Strings within restaurantMenu?

import java.util.HashMap;

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

	HashMap<String, Integer> restaurantMenu = new HashMap<String, Integer>();

	restaurantMenu.put("Turkey Burger", 13);
	restaurantMenu.put("Naan Pizza", 11);
	restaurantMenu.put("Cranberry Kale Salad", 10);

	System.out.println(restaurantMenu.size() );
for(String food: restaurantMenu.keySet()) {


		System.out.println("A " + food + " costs " + restaurantMenu.get(food) + " dollars.");

	}

}

}


Replace this line with your code.


#2

You're iterating through the keys, assigning each key to that variable. The HashMap has no awareness of that variable, the loop is just repeatedly asking for next key and assigning it to your variable.


#3

i think i get it, i may need to flow chart this program to get a full understanding, but the assigning of each key to the variable food is sensible, thanks!


#4

i have the same problem can somebody plz help me