Getting dynamic with arrays

As we discussed at the beginning of all this array stuff, if we need to declare and initialize each element of an array individually, there isn't a huge amount of benefit to an array over regular variables. Let's look at an example of declaring and initializing arrays dynamically.

Dynamic array example

Let's make a simple dynamic array example. You can get the working project for this example in the download bundle. It is in Chapter 12/Dynamic Array Example/MainActivity.java.

Create a project with an empty Activity and call the project Dynamic Array Example. Leave the Activity name as the default MainActivity as we will not be revisiting this project we are not concerned about using memorable names.

Type the following code just after the call to super.onCreate() in the onCreate method. See if you can work out what the output will be before we discuss it and analyze the code.

// Declaring and allocating in one step
int[] ourArray = new int[1000];

// Let's initialize ourArray using a for loop
// Because more than a few are lots of typing!

for(int i = 0; i < 1000; i++){

   // Put the value into our array
   // At the position determined by i.
   ourArray[i] = i*5;

   // Output what is going on
   Log.d("info", "i = " + i);
   Log.d("info", "ourArray[i] = " + ourArray[i]);
}

Run the example app, remembering that nothing will happen on the emulator screen as we send the output to the logcat window in Android Studio. Here is the output:

info﹕ i = 0
info﹕ ourArray[i] = 0
info﹕ i = 1
info﹕ ourArray[i] = 5
info﹕ i = 2
info﹕ ourArray[i] = 10

... 994 iterations of the loop removed for brevity.

info﹕ ourArray[i] = 4985
info﹕ i = 998
info﹕ ourArray[i] = 4990
info﹕ i = 999
info﹕ ourArray[i] = 4995

First, we declared and allocated an array called ourArray to hold up to 1000 int values. Notice that this time we did the two steps in one line of code.

int[] ourArray = new int[1000];

Then we used a for loop that was set to loop 1000 times:

(int i = 0; i < 1000; i++){

We initialized the spaces in the array, starting at 0 through to 999 with the value of i multiplied by 5. Like this.

ourArray[i] = i*5;

Then to prove the value of i and the value held in each position of the array we output the value of i followed by the value held in the corresponding position in the array. Like this.

Log.i("info", "i = " + i);
Log.i("info", "ourArray[i] = " + ourArray[i]);

And all this happened 1000 times, producing the output we have seen. Of course, we have yet to use this technique in a real-world game, but we will use it soon to make our Bullet Hell game a little more hell-like.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.31.26