Library contents

Java List.get, List.size and List.isEmpty

Read an element by its zero-based position. Check size or isEmpty when the requested position might be unavailable.

A simple example

List.get, List.size and List.isEmpty

  1. Start with A, B, C
  2. Do this Read the second element
  3. Result B
Counting A as the first element puts B next in the sequence.

Syntax

Java syntax
names.get(index)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Read the second name on the pickup roster

A teacher calls children in their recorded pickup order. The office asks for the second name on the roster, so the teacher checks that the list contains at least two entries before reading it.

From the programvar names = List.of("Asha", "Mira", "Sam")
ResultMira
Main.java
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var names = List.of("Asha", "Mira", "Sam");
        if (names.size() >= 2) System.out.println(names.get(1));
    }
}
Output
Mira

The second name has index one. The size check keeps a short roster from causing an out-of-bounds error.

Advertisements

Handle an empty pickup roster

An after-school club starts a fresh pickup roster each morning. Until a family registers, its display needs a message that can be shown without reading a nonexistent first entry.

From the programList<String> names = List.of()
ResultNo pickups
Main.java
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        List<String> names = List.of();
        System.out.println(names.isEmpty() ? "No pickups" : names.get(0));
    }
}
Output
No pickups

The empty branch is selected before get is evaluated.

Prepare the next workshop roster

A teacher reads a workshop roster in arrival order. Who or what occupies the second position? Count from the front of the list.

GivenMira · Ivo · Bea
Worked resultIvo

What to watch for

The index must be at least zero and strictly smaller than size. Frequent indexed access can be expensive on a linked list.

Documentation for List.get, List.size and List.isEmpty