Arrays
Array: An indexed structure that holds multiple values of the same type
● Arrays have a fixed size
● Index an array to get or set a value in the list
● Array indices, like string indices, start from 0
● Arrays can be created to hold primitive types or objects
Constructing an Array
<element type>[] <name> = new <element type>[<length>];
● The element type and length are both fixed
● Note: When an array is created, each element is auto-initialized to a default value (the
equivalent of 0 for that data type)
Accessing an element in an array
<name>[<index>]
● Use this expression to get or set an element of the array.
● ie:
ages[1] = 180; or Syste,.out.println(ages[1] + ages[2]);
Looping through elements in an array
for (int i = 0 i < arrayName.length; i++) {
// … do something with arrayName[i]
}
* Note: .length is used for Arrays!
Note - passing arrays to methods
When passing an array to a method, the array itself is not copied
● Instead, the pointer to the array is copied
● Thus, you can modify contents of an array from within a method
Quick array initialization
type[] name = {value, value, …, value};
- Useful when you know what the array’s elements will be
- The compiler figures out the size by counting the values
Limitations of arrays
● You cannot resize an existing array
● You cannot compare arrays with ++ or .equals
● An array does not know how to print itself
Printing an Array
Arrays.toString accepts an array as a parameter and returns a String representation of its
elements.
System.out.println (Arrays.toString(arrayName));
● Must import java.util.*;
For-Each Loop
● If you want to access each element in an array without changing the values
for(<type> <name> : <array>) {
<statement>;
<statenent>;
…
}
● The above statement is read as “for each <type><name> in <array> perform the
following statements…”
Syntax
To declare a two-dimensional array:
type[][] name = new type[rows][columns];
ex: int[][] numbers = new int[2][3];
Assignment/Access
To assign elements
name[row][col] = <value>;
To access
name[row][col]
To print
Arrays.deepToString(name)
Traversing Multidimensional Arrays
- Traverse 2D arrays using Nested for Loops
- The outer loop moves through the ROWS (top to bottom)
- The inner loop moves through the COLUMNS (left to right)
- Called “Row Major Order” on AP Exam
int[][] grid = new int[x][y];
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
//do something with element grid[i][j];
}
}
Note: grid[i] refers to row i of grid
grid[i].length = number of items in the current row or number of columns (if grid is rect)