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
- Start with A, B, C
- Do this Read the second element
- Result B
Syntax
names.get(index)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRead 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.
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));
}
}
Mira
The second name has index one. The size check keeps a short roster from causing an out-of-bounds error.
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.
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));
}
}
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.
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.