Game Development Reference
In-Depth Information
Arrays can actually be used to store anything: variables, numbers, strings, objects, methods, or even
other arrays. You can think of arrays as big storage containers in which everything inside is indexed
with a number. You'll take a look at some practical examples of how this works.
Before you can use an array, you need to instantiate it using the jas keyword. If you want to create an
empty collection jar for the cat to collect bugs with, you can create one like this:
lner]par]n[_khha_pekjF]n6=nn]u7
[_khha_pekjF]n9jas=nn]u\$%7
[_khha_pekjF]n9WY7
Arrays contain their objects using square brackets (the array access operator) that you looked at ear-
lier in the chapter. A pair of empty brackets means that the array is empty.
You can initialize the array so that it's already filled with objects:
[_khha_pekjF]n9Wbhu(ikomqepk(^aaY7
All objects in an array are numbered sequentially, starting with zero. These numbers are called index
numbers . In the preceding example, bhu has an index number of ,, ikomqepk has an index number of
-, and ^aa has an index number of ..
You can find out which object is at which index number using the array access operator. Here's an
example:
[_khha_pekjF]nW-Y
This has the value of ikomqepk because ikomqepk has an index number of -.
It's really very simple. An array is just a numbered list of things known as elements . Figure 9-24 illus-
trates an empty array compared with an array with three elements.
A. An empty array
B. An array with three elements
[_khha_pekjF]n9WY
[_khha_pekjF]n9Wbhu(ikomqepk(^aaY
,*bhu
-*ikomqepk
.*^aa
Use the array access operator to access the elements
in an array.
[_khha_pekjF]nW,Ynabanopkbhu
[_khha_pekjF]nW-Ynabanopkikomqepk
[_khha_pekjF]nW.Ynabanopk^aa
Figure 9-24. Arrays and array elements