Reference · module 4
Arrays and lists
Everything this module explains, on one page.
Arrays
Store several values of one type in an array.
- An array holds a fixed number of values of one type: int[] scores = {90, 75, 60}; The square brackets after the type say it is an array.
- Elements are counted from 0: scores[0] is 90 and scores[2] is 60. Reading scores[3] stops the program with ArrayIndexOutOfBoundsException.
- scores.length gives the size — without brackets, because it is a field, not a method. The size is fixed: new int[5] creates five zeros and can never grow.
The mistake you are about to make
scores.length()
scores.length
Strings use length() with brackets, so arrays seem to need them too. For arrays length is a field and takes no brackets.
ArrayList
Use a list that can grow and shrink.
- When the number of items changes, use an ArrayList: ArrayList<String> names = new ArrayList<>(); The type in angle brackets says what the list holds.
- names.add("Ana") appends, names.get(0) reads the first item, names.size() gives the count, and names.remove(0) deletes the first. Indexes still start at 0.
- Lists hold objects, not primitive types, so write ArrayList<Integer> rather than ArrayList<int>. Java converts between int and Integer automatically.
The mistake you are about to make
ArrayList<int> nums
ArrayList<Integer> nums
int is the number type everywhere else, so it goes in the brackets. Generic types need objects, and the object version of int is Integer.
Looping over collections
Go through every element with a for-each loop.
- for (String name : names) { ... } runs the body once for every element, with name holding each one in turn. It works for arrays and lists alike.
- To total or count, keep a variable outside the loop: int sum = 0; for (int s : scores) { sum += s; }. It must be declared before the loop to survive after it.
- for-each gives values but not positions. When you need the index — to print item 1, item 2 — use a normal for loop with i from 0 to length.
The mistake you are about to make
for (int s : scores) { int sum = 0; sum += s; }
int sum = 0; for (int s : scores) { sum += s; }
The sum belongs to the loop's work, so it gets declared inside. Then it resets to 0 on every round and does not exist after the loop.