JAVA / CHAPTER 07
Arrays and ArrayLists
IntermediateTraverse fixed arrays, resizable lists, and two-dimensional structures.
By the end of this chapter
- Choose arrays or ArrayLists
- Remove list elements safely
- Traverse ragged two-dimensional arrays
The idea
An array has a fixed length and zero-based indices. An ArrayList can grow or shrink, and its size is obtained with a method instead of a field. Generics describe its element type, such as ArrayList<Integer>; primitive int values are boxed when stored there. Replacing an element preserves its position, while removing one shifts later elements left and changes subsequent indices.
A two-dimensional Java array is an array of row references. Rows can have different lengths, so each inner loop should use the current row length. When deleting list entries during traversal, iterate backward or carefully adjust the index. A forward loop that increments immediately after removal can skip the next candidate.
public class Main {
public static void main(String[] args) {
int[][] rows = {{2, 4}, {7}, {1, 3, 5}};
int total = 0;
for (int r = 0; r < rows.length; r++)
for (int c = 0; c < rows[r].length; c++)
total += rows[r][c];
System.out.println(total);
}
}22
The outer loop selects each row. The inner bound adapts to row lengths two, one, and three, avoiding invalid positions.
Try it yourself
Write a method that returns the largest row sum of a nonempty ragged int[][] with nonempty rows.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING