| Index | Android apps - Arrays |
This is all Java. By the way, do NOT try to access past the end of an array (by using a subscript larger than the array size). This will bomb you out of the app when running.
| Define array with size |
| Define two dimensional array |
| Define array and specify size later size |
| Define and initialise array |
| Copying one array to another |
| Number of elements |
It doesn't have to be "public static" of course. But that means that you can use it in other Java classes, which tend to proliferate in an Android app. You often use arrays in a Grid, for example. To use this array:
To use this array:
You may want to define an array as "public static", but change its size dynamically in the program, which will be in a method, and you can't define things as "public static" in a method. Sigh. So define it like this in the "global variables" (outside all the method, such as before the first one):
and then in a method somewhere, you say:
and you can make "arraySize" what you want, or even do this several times in different places. Distinctly useful.
A good way to define an array is to initialise it at the same time, especially if all elements are different, and don't change. For example, this sets up an array of pictures (different coloured blocks, as it happens).
The number of elements is worked out by Java from the number of initialisations - so 16 in this case.
You can do this in two stages (as above), with the "public static" definition outside the methods, and the initialisation done later, inside a method:
You could set up a loop, but AndroidStudio flags up a warnung (sigh!). It wants you to use this
This copies "array", starting at element 0, to "array2", starting at element 0, for "length" number of elements.
You can access the number of elements in an array, which can be useful in a "for" loop;
"array.length" is not the length of the individual elements added together, but just the number of elements.
© Jo Edkins 2016 - Index to Android app index