WeCodeAcademy

Java ArrayList

An ArrayList is a resizable list. Unlike an array, it can grow and shrink. You must use object types such as Integer instead of int inside it.

ExampleJava
import java.util.ArrayList;
import java.util.Collections;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    System.out.println(cars);          // [Volvo, BMW, Ford]
    System.out.println(cars.get(1));   // BMW
    cars.set(0, "Audi");
    cars.remove("Ford");
    System.out.println(cars.size());   // 2
    Collections.sort(cars);
    System.out.println(cars);          // [Audi, BMW]

    ArrayList<Integer> nums = new ArrayList<>();
    nums.add(5); nums.add(1); nums.add(3);
    int sum = 0;
    for (int n : nums) sum += n;
    System.out.println("sum = " + sum);
  }
}
Output
[Volvo, BMW, Ford]
BMW
2
[Audi, BMW]
sum = 9
Quick check

What is the advantage of an ArrayList over an array?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.