In Java, set(index, element)replaces the element at a position in an ArrayList with a new one and returns the element that was there before.
Unlike add(index, e), set does not insert: no elements move and the size stays the same. The index must already exist, so you cannot use set to make a list longer.
An instance method of java.util.ArrayList (Java 1.2+): a resizable-array list with index access that allows null and duplicates and is not thread-safe.
Syntax
Pass the index to replace and the new value.
Java
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
String old = list.set(1, "B"); // old = "b", list = [a, B, c]
list.set(3, "d"); // IndexOutOfBoundsException (no index 3)
Call
What it does
list.set(i, e)
Replaces the element at i; returns the old one.
list.add(i, e)
Inserts at i; the old element moves right.
list.set(i, list.get(i) + 1)
Updates a value based on itself (for a List<Integer>).
Collections.swap(list, i, j)
Swaps two positions using set calls.
set runs in constant time. It is not a structural change (the size does not change), so it does not cause ConcurrentModificationException in a loop that is walking the list.
Library declarations
Java
// java.util.ArrayList<E>
public E set(int index, E element)
// Declared in List<E>
Read, compute, write. For each index, get(i) reads the score, * 2 doubles it, and set(i, ...) stores the result back.
Boxing round trip. The Integer is unboxed for the multiplication, and the result is boxed again when it is stored.
Safe during the loop.set does not change the size, so the loop visits every element exactly once.
No appending.set(3, 0) on a three-element list throws IndexOutOfBoundsException; only add can grow a list.
Frequently Asked Questions
The element that was at that index before the call. You can ignore it if you do not need it.
set(i, e) replaces the element at i and keeps the size. add(i, e) inserts a new element at i, shifts the rest right, and increases the size by one.
No. The index must be less than size(). set(size(), e) throws IndexOutOfBoundsException; use add(e) instead.
Yes. set is not a structural change, so it does not cause ConcurrentModificationException. Inside an iterator loop you can also use ListIterator.set().
Yes. That list cannot change size, but its elements can be replaced, and the change writes through to the backing array.