Library contents

Java List.add and List.addAll

Insert one stop at a position or insert an entire collection there in encounter order.

A simple example

List.add and List.addAll

  1. Start with A, C
  2. Do this Insert B between them
  3. Result A, B, C
Inserting at the middle shifts C one place to the right.

Syntax

Java syntax
stops.addAll(index, extraStops)
Run these examples in Java

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

java Main.java

Insert two pickup stops before the depot

A shuttle normally travels straight from the school to the depot. The dispatcher adds two afternoon pickups and needs them to appear in the supplied order before the final stop.

ResultSchool, Hall, Pool, Depot
Main.java
import java.util.ArrayList;
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var stops = new ArrayList<>(List.of("School", "Depot"));
        stops.addAll(1, List.of("Hall", "Pool"));
        System.out.println(String.join(", ", stops));
    }
}
Output
School, Hall, Pool, Depot

Inserting at position one shifts the depot to the right. The hall remains ahead of the pool.

Advertisements

Give an urgent repair the next slot

A repair desk has already booked two routine jobs. A boiler failure needs immediate attention, so the coordinator inserts it at the front of the queue.

ResultBoiler
Main.java
import java.util.ArrayList;
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var jobs = new ArrayList<>(List.of("Tap", "Lamp"));
        jobs.add(0, "Boiler");
        System.out.println(jobs.getFirst());
    }
}
Output
Boiler

Adding at zero makes the boiler repair the first job and preserves the two existing jobs.

Extend a reading list

A class has chosen one novel and adds two more titles. The desk adds the new entries after the existing ones. Read the resulting sequence in its recorded order.

GivenFern + Tide, Sky
Worked resultFern · Tide · Sky

What to watch for

Insertion shifts later positions. The list must support structural changes.

Documentation for List.add and List.addAll