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...