ESC
Type to search...
Dashboard / Java notes / Concepts / Basics / Part i

08 - Lists

P1 · Updated · Source
#java/basics #l0 #concept #must-know #status/known

Lists (ArrayList)

What is it?

A List (specifically ArrayList) is a dynamic, ordered collection of elements. Unlike a regular array, it can grow and shrink as you add or remove items - you don’t have to declare the size upfront.

Why does it exist?

Arrays have a fixed size - once created, you can’t add more slots. ArrayList solves this: it automatically resizes itself. Use it whenever you need to store an unknown or variable number of items.

How does it work?

Import and Create

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();
  • ArrayList<String> → a list that holds String values
  • The <String> part is the type parameter - it tells Java what type of elements the list stores
  • new ArrayList<>() → creates the actual list object (starts empty)

Note The type inside <> must be a class type, not a primitive. Use Integer instead of int, Double instead of double:

ArrayList<Integer> numbers = new ArrayList<>();
ArrayList<Double>  prices  = new ArrayList<>();

Adding elements - .add()

names.add("Alice");
names.add("Bob");
names.add("Charlie");
// List is now: [Alice, Bob, Charlie]

Getting elements - .get(index)

Lists are zero-indexed - the first element is at index 0:

System.out.println(names.get(0)); // Alice
System.out.println(names.get(1)); // Bob
System.out.println(names.get(2)); // Charlie

Size - .size()

System.out.println(names.size()); // 3

Removing elements - .remove()

names.remove("Bob");
// List is now: [Alice, Charlie]

names.remove(0); // removes by index (removes "Alice")
// List is now: [Charlie]

Warning For ArrayList<Integer>, .remove(2) removes the element at index 2, not the value 2. To remove by value, use .remove(Integer.valueOf(2)).

Checking if an element exists - .contains()

boolean found = names.contains("Alice"); // true or false

Looping Over a List

Using a for loop with index

for (int i = 0; i < names.size(); i++) {
    System.out.println(names.get(i));
}

Using a for-each loop (cleaner)

for (String name : names) {
    System.out.println(name);
}

Read for (String name : names) as: “for each String called name in names…”

Common ArrayList Methods at a Glance

Method What it does
.add(value) Adds value to the end
.add(index, value) Inserts value at a specific index
.get(index) Returns element at index
.set(index, value) Replaces element at index
.remove(index) Removes element at index
.remove(value) Removes first occurrence of value
.size() Returns number of elements
.contains(value) Returns true if value is in the list
.isEmpty() Returns true if list has no elements
.clear() Removes all elements

Real Example - collecting numbers and computing sum

import java.util.ArrayList;
import java.util.Scanner;

public class NumberCollector {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Integer> numbers = new ArrayList<>();

        while (true) {
            String input = scanner.nextLine();
            if (input.equals("done")) break;
            numbers.add(Integer.parseInt(input));
        }

        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        System.out.println("Sum: " + sum);
        System.out.println("Count: " + numbers.size());
    }
}

Gotchas

  • Accessing an index that doesn’t exist throws IndexOutOfBoundsException - always check .size() before accessing
  • ArrayList is 0-indexed - last element is at .size() - 1
  • You can’t store primitives directly - use wrapper types: Integer, Double, Boolean
  • Lists maintain insertion order - elements come out in the same order you put them in

Related: Loops, Methods, Objects, String