Arrays and ArrayList
Control flow and methods12 min readLesson 3 of 4
3.1 Arrays keep a fixed sequence
An array holds several values of one type under a single name. Its length is fixed when it is created. Each value sits at an index, and indexes start at 0. An array of length 4 has valid indexes 0, 1, 2, and 3.
You can create an array with new int[4], which fills every slot with the default value for int, or with an initializer list such as {72, 85, 90, 66}. Once the array exists, scores[0] reads the first element and scores[0] = 80; replaces it.
For an array named scores, the expression scores.length gives the number of slots. It is a field, not a method, so it has no parentheses. The JVM checks indexes at runtime and throws ArrayIndexOutOfBoundsException for an index below 0 or at least the length.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] scores = {72, 85, 90, 66};
System.out.println(scores.length);
System.out.println(scores[0]);
System.out.println(Arrays.toString(scores));
}
}Output
4 72 [72, 85, 90, 66]
3.1.1 Traversing an array
A standard for loop is the choice when you need the index. It can read values, write new values, or compare neighbouring elements. Start at 0 and stop before length:
for (int i = 0; i < scores.length; i++) { ... }
An enhanced for loop reads every element without exposing the index:
for (int score : scores) { ... }
For primitive elements, the loop variable is a copy of the element. Changing score inside the body does not change the array. Use the indexed loop when you need to assign back to scores[i].
Arrays.toString(array) returns a readable string such as [72, 85, 90, 66]. It needs import java.util.Arrays; at the top of the file. Printing the array directly with println shows an identity-like value, not its contents.
public class Main {
public static void main(String[] args) {
int[] scores = {72, 85, 90, 66};
int total = 0;
for (int score : scores) {
total += score;
}
double average = (double) total / scores.length;
System.out.printf("Average: %.2f%n", average);
}
}Output
Average: 78.25
3.1.2 Common array tasks
Sums and averages follow a simple pattern. Start an accumulator at 0, loop over the values, and add each one. After the loop, divide by the length. Cast at least one operand to double if you want a decimal average; otherwise integer division discards the fraction.
A maximum starts as the first element, then each later element replaces it when the element is larger. This assumes the array is not empty. For an empty array, handle the case separately before reading values[0].
A search compares each element with a target and records the index when it finds a match. Stop with break after the first match if only the first match matters. Arrays do not have a built-in indexOf method for primitive values.
public class Main {
public static void main(String[] args) {
int[] values = {14, 9, 31, 22};
int largest = values[0];
for (int value : values) {
if (value > largest) {
largest = value;
}
}
System.out.println("Largest: " + largest);
}
}Output
Largest: 31
3.1.3 Two-dimensional arrays
A two-dimensional array is an array of arrays. int[][] grid = new int[2][3]; creates two rows and three columns. Access an element as grid[row][column]. The first index chooses a row, and the second chooses a position inside that row.
grid.length is the number of rows. grid[0].length is the number of columns in the first row. Nested loops traverse it: the outer loop moves through rows and the inner loop moves through columns. Use the row's own length in the inner condition if rows can differ in size.
Printing a 2D array with Arrays.toString(grid) is not enough, because each element is itself an array. Arrays.deepToString(grid) displays the nested contents.
public class Main {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
if (col > 0) {
System.out.print(" ");
}
System.out.print(grid[row][col]);
}
System.out.println();
}
}
}Output
1 2 3 4 5 6
3.1.4 ArrayList grows as needed
An ArrayList is a resizable list from java.util. It stores objects, and a type parameter says what kind: ArrayList<String> names = new ArrayList<>();. The empty angle brackets let the compiler infer the same type.
The common operations are add(value), get(index), set(index, value), remove(index), and size(). Adding appends or inserts at an index. contains(value) checks equality. Printing an ArrayList displays its elements in brackets, such as [Read, Review].
An ArrayList cannot store primitives directly. Use the wrapper classes Integer, Double, and Character. Java converts between int and Integer with autoboxing and unboxing in most contexts, so marks.add(40) works on an ArrayList<Integer>.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> tasks = new ArrayList<>();
tasks.add("Read");
tasks.add("Practice");
tasks.add("Review");
tasks.remove("Practice");
System.out.println(tasks);
System.out.println(tasks.size());
System.out.println(tasks.get(1));
}
}Output
[Read, Review] 2 Review
3.1.5 Choosing between an array and an ArrayList
Use an array when the number of elements is known and will not change. Use an ArrayList when items are added or removed as the program runs. The choice affects syntax: arrays use array.length and array[i]; lists use list.size() and list.get(i).
The two remove methods on ArrayList can surprise you. list.remove(1) removes the element at index 1. list.remove(Integer.valueOf(1)) removes the first occurrence of the value 1 from an ArrayList<Integer>. The compiler chooses the overload from the argument type.
An ArrayList can still be printed, searched, and sorted with library methods later. For now, master the four operations you need most: add, read, replace, and remove.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<>();
marks.add(40);
marks.add(55);
marks.add(70);
marks.remove(0);
marks.set(1, 75);
int total = 0;
for (int mark : marks) {
total += mark;
}
System.out.println(marks + " total=" + total);
}
}Output
[55, 75] total=130
3.1.6 Practice
- Create an array of five marks and print its length, first value, and last value.
- Sum the array with a
forloop and calculate the average with a cast. - Find the smallest value in the array without sorting it.
- Create a 2D array with two rows and three columns, then print it row by row.
- Build an
ArrayList<String>of three tasks, remove the middle one, add a new task, and print the result.
For step 3, start with the first element and compare every later element. Test the program with negative numbers as well as positive ones so the starting value is not doing hidden work.
