Array & Matrix
Intent
An array stores a sequence of values that are all of the same type. The method that we use to refer to individual values in an array is to number and then index them—if we have n values, we think of them as being numbered from 0 to n−1.
Problem
We want not just to store values but also to be able to quickly access each individual value.
Example
- Making an array in a Java program
double[] a; // declare the array a = new double[n]; // create the array for (int i = 0; i < n; i++) // elements are indexed from 0 to n-1 a[i] = 0.0; // initialize all elements to 0.0
- Array initialization also can be done at compile time using curly braces
String[] SUITS = { "Clubs", "Diamonds", "Hearts", "Spades" };
- Matrix operations. Typical applications in science and engineering involve implementing various mathematical operations with matrix operands. For example, we can add two n-by-n matrices as follows:
double[][] c = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { c[i][j] = a[i][j] + b[i][j]; } }
Rules of Thumbs
- the code
a[i]
refers to elementi
of arraya[]
. - Zero-based indexing. We always refer to the first element of an array
a[]
as a[0]
, the second asa[1]
, and so forth. - Array length. Once we create an array, its length is fixed.
- Memory representation. When you use new to create an array, Java reserves space in memory for it (and initializes the values). This process is called memory allocation.