Arrays are one of the simplest data structures. Typically they are built-in to most modern programming languages. An array is an arrangement of data in a particular order. They map numbers (these are the indices of an array) to data items (the elements).
Here’s an image depicting what an array looks like conceptually:
The type of data stored inside of an array is declared in a programs source code when declaring the array. Some (often dynamically typed) programming languages allow for declaring arrays without specifying a particular data type. Traditionally arrays are defined to be a static (fixed) length that cannot be changed during the programs run time. Some programming languages allow for the length (the amount of items an array can contain) of an array to be changed during run-time. An array can be zero (indexes range from 0 to size-1) or one indexed (indexes range from 1 to size). Arrays can also be multi-dimensional (ie. 2, 3, or N dimensional). Arrays are often used to implement other data structures.
Advantages:
Disadvantages:
So without further ado lets get to some array examples!!!
Sample declaration of an array of integers of size 10 named “arr”:
Alternate declaration style:
Sample declaration of an array of Strings of size 10:
Declare an array of integers of size 10 and set each index so that the index is equal to the element at that index:
Get the element of the first index of an array of integers (arrays in Java are indexed starting at zero):
Get the size of an array:
Using the java.util.Arrays class to sort an array:
Using the java.util.Arrays class and System.out.println() function to print out an array to the console:
Initialize a two dimensional array of size 8 by 9 and set all elements to 100:
int[][] marr = new int[8][9];
for(int i = 0; i < 8; i++)
for(int j = 0; j < 9; j++)
marr[i][j] = 100;
Initialize a three dimensional array of size 2 by 3 by 4 and set all elements to 25:
int[][][] threeDimensionalArray = new int[2][3][4];
for(int i = 0; i < 2; i++)
for(int j = 0; j < 3; j++)
for(int k = 0; k < 4; k++)
threeDimensionalArray[i][j][k] = 25;