Java 25 (LTS) reference · List and ArrayList Methods
Java List set() Method
Replace the element at an index and return the old value. The list's size doesn't change.
Java 25 (LTS) Since Java 1.0
Syntax
list.set(index, element)
Parameters
| Parameter | Description |
|---|---|
indexint |
Position to replace. |
elementE |
New value. |
Return value
The previous element.
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> tasks = new ArrayList<>(List.of("draft", "review", "publish"));
String old = tasks.set(1, "edit");
System.out.println(old + " -> " + tasks);
}
}
Output
review -> [draft, edit, publish]
Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> prices = new ArrayList<>(List.of(10, 20, 30));
for (int i = 0; i < prices.size(); i++) prices.set(i, prices.get(i) * 2);
System.out.println(prices);
}
}
Output
[20, 40, 60]
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
list.get()· Return the element at an index (0-based). Throws IndexOutOfBoundsException for an invalid index.list.add()· Append an element to the end of a list, or insert it at an index, shifting later elements right.- Java ArrayList · tutorial