Java Reference
In-Depth Information
Figure 1—Array of Blocks
Try This Yourself
Now it's your turn. Make a small change to reverse the order of the tower's
elements, so that the anvil is on the bottom and the stone is on the top.
Change the for loop around to do this. Instead of going from 0 to < 5, change
the loop to go from 4 down to >= 0. Hint: Subtraction might work better than
addition in this case.
Rebuild, stop, start, and try the /arrayofblocks command again.
Now you know how to work with for loops and indexes, but to be honest, this
is an old corner of Java, and it's a tad musty. Array objects are handy, but
there's perhaps a better choice.
Use a Java ArrayList
An ArrayList in Java also keeps track of a list of values, just like a simple Array
does. ArrayList s are a little messy to declare but simple enough to use, and
much more flexible and a bit safer than plain old Array objects. You can add
and delete from the ArrayList as many times as you want; it's not a fixed length
and will grow or shrink as needed.
Here's an example of an ArrayList that will hold Player objects:
List <Player> myPlayerList = new ArrayList <Player>();
Search WWH ::

Custom Search