Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

List.set()

Replaces the list element at an index.

Available since: Java 1.2

Syntax

E set(int index, E element)

Parameters

ParameterTypeDescription
indexintThe position of the element to replace.
elementEThe new value.

Return value

EThe element that was at this position before.

Examples

Replacing the second element:

void main() {
    List<String> colors = new ArrayList<>(List.of("red", "green", "blue"));
    String old = colors.set(1, "yellow");
    IO.println(old);
    IO.println(colors);
}

Output:

green
[red, yellow, blue]

Notes

The list size does not change: set() replaces rather than inserts. To insert use add(index, element). The index must exist, otherwise IndexOutOfBoundsException is thrown.

See also

  • List.get() — Returns the list element at an index.
  • List.add() — Adds an element to the end of a list or at a given position.
  • List.replaceAll() — Replaces every list element with the result of a function.

In the tutorial

  • Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.

Thanks for reading!

Donate to the site — we work hard for you.