Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Matthew Francis
6,967 PointsSuper Newbie - What are HashMaps and when to use them?
After reading stackoverflow/videos on youtube, I still have no idea what it does. Could soemone perhaps dumb it down for me?
An example of HashMaps:
import java.util.HashMap;
public class Restaurant {
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.get("Naan Pizza") );
}
}
2 Answers
Steve Hunter
57,712 PointsHi Matthew,
A HashMap stores a collection of key/value pairs. I found this article useful.
The documentation is a little opaque, though!
This also contains useful information.
Steve.
Jeremy Hill
29,567 PointsAfter reading about them on stackoverflow you are probably already familiar with the terms: value and key, so let me give you an example where you would want to use one. If you were wanting to create a video game with fight characters and you wanted to give each character a weapon with varying damage points you want to use a HashMap. You would set the "key" to the weapon (e.g. sword, bow and arrow, etc.) and the "value" to the damage that it would inflict on the opponents in battle. This would make the association between the two elements. So when I would use the HashMap's get method on one of the keys (e.g. "sword") it would return the number of damage points.
I hope this helps.