Basic

Arrays and Lists

Store ordered collections with arrays and ArrayList.

What you will see

1

About 2 min of reading

Try It

Store ordered data with a fixed-size array and a growable ArrayList. Read elements by index, grow the list dynamically, and see the difference between the two.

1

Declare a fixed-size int array and modify an element by index. Arrays are zero-based, so the first slot is [0]. Print a changed element and the fixed length.

class Main { public static void main(String[] args) { int[] nums = {1, 2, 3}; nums[0] = 10; System.out.println(nums[2]); System.out.println(nums.length); } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
3 3
The length is fixed when you create the array. Asking for nums[10] throws ArrayIndexOutOfBoundsException, there is no such slot.
2

Read every element of an array with an indexed for loop, using .length as the boundary. Print each fruit in turn.

class Main { public static void main(String[] args) { String[] fruits = {"apple", "banana"}; for (int i = 0; i < fruits.length; i++) { System.out.println(fruits[i]); } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
apple banana
The condition is i < fruits.length, not <=, otherwise the last read (i == length) is out of bounds.
3

Use an ArrayList when you do not know how many items you will have. Add two strings, remove the first, then print the new size, it resizes itself.

import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList list = new ArrayList<>(); list.add("a"); list.add("b"); list.remove(0); System.out.println(list.size()); } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
1
ArrayList holds objects, so plain values like int are auto-boxed to Integer. Prefer the List interface as the type for flexibility.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

Elements are stored in contiguous slots; arrays fix size at creation while ArrayList resizes automatically.
1 Create array or ArrayList
↓
2 Add elements by append or index
↓
3 Read/write by position
↓
4 ArrayList grows backing array when full
Why this works
Common ArrayList operations
List<Integer> numbers = new ArrayList<>();
numbers.add(5);        // append
numbers.set(0, 9);     // replace by index
int first = numbers.get(0);   // read
boolean has = numbers.contains(9);

add appends, set replaces, get reads, contains tests membership. Removal by value or index is supported. Under the hood the backing array grows by ~50% when full.

When you have a choice

Arrays vs ArrayList

FeatureArrayArrayList
SizeFixedDynamic
TypePrimitives or objectsObjects only
SpeedFasterSlightly slower
Methods.length field.size(), .add(), .remove()

Choose an array for fixed-size, high-performance needs; choose ArrayList when the count changes. ArrayList stores objects, so primitives are auto-boxed (int -> Integer).

Examples

Declaring and indexing arrays

Fixed-size arrays

int[] nums = {1, 2, 3};
nums[0] = 10;   // modify
System.out.println(nums[2]);   // 3
System.out.println(nums.length);   // 3

Arrays have a fixed size set at creation. Indices start at 0. Accessing an out-of-range index throws ArrayIndexOutOfBoundsException.

Iterating an array

Reading every element

String[] fruits = {"apple", "banana"};
for (int i = 0; i < fruits.length; i++) {
    System.out.println(fruits[i]);
}
for (String f : fruits) {
    System.out.println(f);
}

Use the indexed form when you need the position; use for-each when you only need values.

ArrayList dynamic list

Growing collections

import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.remove(0);
System.out.println(list.size());   // 1

ArrayList is a resizable array. Unlike a plain array, it grows and shrinks automatically. Use the List interface as the type for flexibility.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Loops and Iteration
Previous Lesson
Loops and Iteration
Next Lesson
Methods and Functions
Methods and Functions →