As we discussed at the beginning of all this array discussion, 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.
Let's make a really simple dynamic array example. You can get the working project for this example in the download bundle. It is located at Chapter 13/Dynamic Array Example/MainActivity.java
.
Create a project with a blank Activity and call it Dynamic Array Example
.
Type the following just after the call to setContentView
in onCreate
. Check whether you can work out what the output is 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 variables is a lot of typing! for(int i = 0; i < 1000; i++){ // Put the value of ourValue into our array // At the position determined by i. ourArray[i] = i*5; // Output what is going on Log.i("info", "i = " + i); Log.i("info", "ourArray[i] = " + ourArray[i]); }
Run the example app, remembering that nothing will happen on the screen, as all the output will be sent to our logcat console 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
We removed 994 iterations of the loop for brevity, and the output will be as follows:
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. Note that this time we performed these 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 demonstrate 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 saw. Of course, we are yet to use this technique in a real-world app, but we will use it soon to make our Note To Self app hold an almost infinite number of notes.
3.133.121.160