Java Reference
In-Depth Information
One last interesting note about variables: notice that at
❶
and
❷
, I used a
new
to make a new variable, as in
towerBase = new Location(towerLoc)
, instead of
just assigning it, as in
towerBase=towerLoc
. Why do you think I did that?
Remember that when you create a variable with
new
, the actual variable is
sitting out in memory someplace, and your name is just a name. So if I had
typed
towerBase = towerLoc
, there would only be one
Location
, with two names.
They wouldn't be separate variables. By typing
towerBase=newLocation(towerLoc)
I made a whole new variable named
towerBase
that has copied the values from
towerLoc
.
If you're planning on changing the values of a variable, and you don't want
to change the original, always make a copy.
The full plugin is in
code/ArrayAddMoreBlocks
. Build, stop, start, and try that now,
building and clearing some towers. Remember, you might need to turn around
and face a different direction to see the tower.
Try This Yourself
Now change the code and add a couple of different building materials. Then
try changing it to use just one material, like
Dirt
perhaps. Or make a nice mix
of
Dirt
and
Grass
. You're in control.
Next Up
In this chapter you've learned the difference between local and global variables.
You can use a simple
Array
or the more flexible
ArrayList
to store a pile of data,
and traverse it using a for-each iterator.
Arrays are great if you don't really care about finding one of the objects in
the array by itself. However, if you care about objects by name—like a
Player
—then you'll need something a little fancier.
In the next chapter we'll cover how to use a
HashMap
to store data by name (or
by
Location
, or by anything else you might need).