Java Reference
In-Depth Information
Figure 2—A HashMap
HashMap s are a great way to store a lot of data that's indexed by a string, just
like a dictionary. You look up a word and get a bunch of data. You can also
use a HashMap to store a bunch of named properties for an object. The nice
part about this is that the property names are just String s. You could add new
properties or delete them while the plugin is running—something that's tough
to do with hard-coded function or variable names.
Let's play with these a bit. Here's a small standalone program where we can
experiment with a HashMap . Maybe you'll make a plugin that implements some
kind of Hunger Games -style contest, where you'd want to have a score for
each player. You'd keep track of each player's score using a HashMap , like this:
HashMap < String , Integer > currentScores = new HashMap < String , Integer >();
public static void addToScore( HashMap < String , Integer > allScores,
String playerName,
int amount) {
int score = allScores.get(playerName);
score += amount;
allScores.put(playerName, score);
Here's how you'd use it:
currentScores.put( "Andy" , 1001);
currentScores.put( "Bob" , 20);
currentScores.put( "Carol" , 50);
currentScores.put( "Alice" , 896);
addToScore(currentScores, "Bob" , 500); "Bob's score is " + currentScores.get( "Bob" ));
Search WWH ::

Custom Search