CKTIS / Java
List.set — Replace a list element by index
`List.set(int,E)` replaces the element at an existing index and returns the old element. It neither changes the list's size nor shifts any other elements.
Version: Java SE 21
Syntax
E set(int index, E element)List.set is an instance method of java.util.List<E>. The signature List.set(int,E) means that list.set(index, element) takes an int index and a new element of type E, and returns the previous element at that index, also of type E.
Indices start at zero. A valid index satisfies 0 <= index < list.size(); outside that range, a list that supports set throws IndexOutOfBoundsException. Unlike add(index, element), set does not insert an element, shift other elements, or change size(). The index list.size() can be used to insert at the end, but not to replace an element.
set is optional: ArrayList supports it, but a list from List.of(...) throws UnsupportedOperationException. Fixed size does not rule out replacement: Arrays.asList(...) supports set with a compatible element, and the change is visible in the array. Depending on the list, a disallowed null can cause NullPointerException, a disallowed type ClassCastException, and another disallowed element property IllegalArgumentException.
subList(from, to) is a view, not a copy: it includes from and excludes to. View indices start at zero, so window.set(i, value) updates index from + i in the backing list if it supports set. If the backing list is structurally modified other than through that view, the view's behavior is undefined.
Examples
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> base = new ArrayList<>(List.of("A", "B", "C", "D", "E"));
List<String> window = base.subList(2, 4);
int sizeBefore = base.size();
String firstOld = window.set(0, "X");
String secondOld = window.set(1, "Y");
System.out.println("old=" + firstOld + ", " + secondOld);
System.out.println("window=" + window);
System.out.println("base=" + base);
System.out.println("size=" + sizeBefore + " -> " + base.size());
}
}
Result
old=C, D window=[X, Y] base=[A, B, X, Y, E] size=5 -> 5
The two `set` calls replace `C` and `D` with `X` and `Y`. Indices `0` and `1` in `window` correspond to `2` and `3` in `base`; the backing list still has `5` elements.
Related lessons
- Java · Lesson 21 · Advanced · Version: 2
- Java · Lesson 54 · Basic · Version: 2
- Java · Lesson 6 · Intermediate · Version: 2
- Java · Lesson 34 · Intermediate · Version: 2