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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

list.set(index, element)

Parameters

ParameterDescription
index
int
Position to replace.
element
E
New value.

Return value

The previous element.

Examples

Replace by index
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.

Update every element
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

VersionChange
Java Java 1.0Added

Was this page helpful?