The Coder's Handbook

Arrays

WHAT IS AN ARRAY?


An array is a type of data structure used to store information. Data structures are used to organize, arrange, and access collections of information. Data structures are called generic classes or template classes, meaning they can be applied to any type of variable.


Arrays are the most basic data structures. Take a moment to look at the diagram above. Take note of the following:

  • The array has a length of 10

  • The index positions start at 0 and end with 9

  • Thus the final index is equal to length - 1


INITIALIZING AN ARRAY

Initializing with a Predefined List


The easiest way to create an array is to use an array initializer. This works well if you know the exact elements you will want in your array when you create it.

Examples

int[] numbers = {3, 5, 2, 21};

String[] words = {"never", "gonna" , "give", "you", "up"};

Initializing with New


Most of the time, you won’t know exactly what data you want to put into your array at the moment you create it. You’ll likely fall into one of the following cases:


  • Your array should start out with some default values, like a blank space or 0.

  • Your array is going to be filled up with data from a file

  • Your array is going to be filled with procedurally generated data.


You may also find that you have too many elements to make the initializer efficient to type. As a result, you’ll often need to create an array and then fill it up using a loop.

Examples

// Filling an array with random data

int[] numbers = new int[200];


for(int i = 0; i < numbers.length; i++)

{

numbers[i] = (int) (Math.random() * 10);

}

// Assigning starting values to each element of an array

String[] words = new String[150];


for(int i = 0; i < numbers.length; i++)

{

words[i] = "";

}

USING ARRAYS

Accessing an element

    • To access an element, you will reference it by its index position:

System.out.println(numbers[3]);

Set an element

    • To set an element, you do the same thing but on the left hand side:

numbers[3] = 74;

Get the length

    • To get the length of an array, you use the length property.

    • Unlike with Strings, this does not have parentheses.

if(numbers.length < 5)

TWO DIMENSIONAL ARRAYS

Rows and Columns

    • A row is a horizontal line of data. Think the motion of rowing a boat.

    • A column is a vertical line of data. Think about the structure of a column holding up a building.

    • Rows are listed before columns when accessing an index position.

Syntax

    • When using a two dimensional array, we simply double everything!

    • Most commonly, we'll make variables or constants to keep track of rows and columns to help our code be more readable.

Examples

final int ROWS = 100;

final int COLS = 50;

char [] grid = new char[ROWS][COLS]


for(int i = 0; i < COLS; i++)

{

for(int j = 0; j < ROWS; j++)

{

grid[i][j] = "-";

}

}


System.out.println(grid[32][45]);

RESOURCES