Java List.set
Replace one element at an existing position. Java returns the value previously stored there.
A simple example
List.set
- Start with A, B
- Do this Replace the second item with C
- Result A, C
Syntax
stops.set(index, newStop)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCorrect the second stop on a shuttle route
A dispatcher spots an outdated address at the second stop on today's shuttle route. The position on the schedule is correct, so only the destination at that position should change.
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", "Park"));
stops.set(1, "Harbor");
System.out.println(stops.get(1));
}
}
Harbor
The first stop stays in place and the second stop now reads Harbor.
Record which volunteer was replaced
A volunteer calls in sick just before a shift. The coordinator assigns a replacement to the same time slot and records both names for the handover.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var shift = new ArrayList<>(List.of("Ravi"));
String previous = shift.set(0, "Nia");
System.out.println(previous + " -> " + shift.get(0));
}
}
Ravi -> Nia
set returns the old name while updating the shift in place.
Correct a lab register
A student signed the lab sheet with a nickname. The second entry must be corrected in place. Which value occupies that position after the change?
What to watch for
Setting a position does not extend the list. Use add when creating a new position.