In this chapter we'll get a little fancier with piles of data and plugin
structure, and add these abilities to your toolbox:
• Keep piles of data in hashes
• Use private to hide your private data, and use public for things
other people should see and use
Use Piles of Variables: HashMap
Use a Java HashMap
HashMap is a funny name. The “hash” part refers to how it works internally; it
really has nothing to do with how you use it.
But the “map” part is about what you'd think: it maps a key, which can be
anything, to a value, which can also be anything.
Other languages might call this a dictionary , an associative array or some
kind of associative memory . They all mean the same thing. With an array,
you use an integer as the index. With a HashMap , you can use any object as
the key, especially String s (see Figure 2, A HashMap , on page 106 ).
We'll use this a lot in the plugins. It's a great way to keep track of players,
cows that you've spawned, or anything else you want. Although it kind of
works like an array, you don't use it the same way. Back when we looked at
an array you learned that you can get and set a value with an index like this:
myList = "Andy" ;
String who = myList;
But you can't use that kind of assignment and bracket notation with a HashMap .
Instead you use its put and get functions. On the plus side, though, now you
can use anything as a key. Most of the time you'll probably use a String . So
suppose you have a HashMap cleverly named myHash .
myHash.put( "Andy" , "www.PragProg.com" );
// Works like myHash["Andy"] = "www.PragProg.com";
String myUrl = myHash.get( "Andy" );
// Works like myUrl = myHash["Andy"];
Now myUrl will have the value of "www.PragProg.com" .