Arrays and ArrayList
Use a fixed-size array or a resizable list and access items by index.
Use an array for a known size
An int[] stores values at zero-based indices. Its length is fixed at creation and available with .length. Reading an index of values.length exceeds the last valid position.
How it works
An array is created with a length that stays fixed. An ArrayList changes its size as items are added or removed. In either one, write the index before reading the value, and remember that the last occupied index is one less than the count.
Use ArrayList for changing size
ArrayList<String> holds a resizable list of strings. Add an item with add, access one with get, and ask how many it contains with size(). Java generics take reference types, so a resizable list of integers uses Integer in its angle brackets.
Code example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> titles = new ArrayList<>();
titles.add("Maps");
titles.add("Weather");
System.out.println(titles.get(0));
System.out.println(titles.size());
}
}Check your understanding
Read the last title in each list. If the list has no titles, return "Empty".
See the example and explanation
- Example 1
- Given
["Maps", "Weather", "Stars"] - Answer
Stars - Example 2
- Given
[] - Answer
Empty
When the size is positive, the last valid index is size() - 1. Check isEmpty() before calling get.