A simple mini-app array example
Let's make a simple working array example. You can get the completed code for this project in the downloadable code bundle. It can be found in the Chapter15/Simple Array Example/MainActivity.kt
file.
Create a project with an Empty Activity project template and call it Simple Array Example
.
First, we declare our array, allocate five spaces, and initialize values to each of the elements. Then, we output each of the values to the logcat window.
This is slightly different to the earlier examples that we have seen because we declare the size at the same time as we declare the array itself.
Add the following code to the onCreate
function just after the call to setContentView
:
// Declaring an array // Allocate memory for a maximum size of 5 elements val ourArray = IntArray(5) // Initialize ourArray with values // The values are arbitrary, but they must be Int // The indexes are not arbitrary. Use 0 through 4 or crash! ourArray[0] = 25 ourArray[1] = 50 ourArray...