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
- Start with A, C
- Do this Insert B between them
- Result A, B, C
Syntax
stops.addAll(index, extraStops)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaInsert 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.
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));
}
}
School, Hall, Pool, Depot
Inserting at position one shifts the depot to the right. The hall remains ahead of the pool.
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.
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());
}
}
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.
What to watch for
Insertion shifts later positions. The list must support structural changes.