Java Reference
In-Depth Information
Compiling and running that in a plugin gives us the expected answer of 520
for Bob. Let's go over the code:
On the line at
❶
you see the call to
new()
that creates a new
HashMap
for us to
use. Since the
HashMap
has to know what we're going to use for a key and a
value, we have to pass in the type names using the angle brackets (
<
and
>
),
just as we did for an
ArrayList
—except here we need to pass in two types: one
for the key (which is a
String
) and one for the value (an
Integer
).
1
With a new
HashMap
named
currentScores
in hand, we can go through and create
some test entries in our hash with player names and their scores. This time,
though, we'll do something a little different.
We're going to make a new helper function that will increment a player's score.
You can see this starting at
❷
. It's a simple function that does three things,
but it's a good habit to get into. Any time you have to do a series of steps a
couple of times, don't write them out and copy and paste. Instead make a
function to do the work for you, then just call the function when you need it.
Our function
addToScore()
is declared to take three arguments: the
HashMap
of
all scores, the string with the player name, and the integer value to add to
the score. With this data, we're doing three steps:
1. Get the current score for the player whose name is in
playerName
(on the
line at
❸
).
2. Increase that score by the amount you passed in as
amount
(at
❹
).
3. Save that newly incremented score back into the hash (at
❺
).
Note that we're not returning any particular value from this function, as it's
declared to be
void
, just like
main
is. Instead it's modifying the
HashMap
that's
passed in; in this case, the global
currentScores
.
Most of the time, though, you'll want functions that return a useful value.
For instance, here's a short, trivial function that adds 10 to any number you
pass in:
public static int
addTen(
int
originalNumber) {
int
newNumber = originalNumber + 10;
return
newNumber;
}
1.
Why
Integer
and not
int
? Because Java. When using collections like
HashMap
and
ArrayList
,
you have to refer to primitive types (
int
,
float
) by their class names,
Integer
and
Float
. The
magic of
autoboxing
takes care of converting from
Integer
to
int
and so on. Just use the
capitalized full names in the angle brackets, and life goes on.