Library contents

Java List.set

Replace one element at an existing position. Java returns the value previously stored there.

A simple example

List.set

  1. Start with A, B
  2. Do this Replace the second item with C
  3. Result A, C
Replacing one element keeps the number of elements at two.

Syntax

Java syntax
stops.set(index, newStop)
Run these examples in Java

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

java Main.java

Correct 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.

ResultHarbor
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", "Park"));
        stops.set(1, "Harbor");
        System.out.println(stops.get(1));
    }
}
Output
Harbor

The first stop stays in place and the second stop now reads Harbor.

Advertisements

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.

ResultRavi -> Nia
Main.java
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));
    }
}
Output
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?

GivenAda · Kit → replace Kit with Kiran
Worked resultKiran

What to watch for

Setting a position does not extend the list. Use add when creating a new position.

Documentation for List.set