Java ArrayList set() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
ArrayList

Definition

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)
CallWhat 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>

Parameters

ParameterDescription
index (int)Position to replace, from 0 to size() - 1.
element (E)The new value. May be null.

Return Value

Return ValueDescription
EThe element previously at index (may be null).

Compare with Similar Methods

Methods that change values in place:

MethodHow it differs
add(i, e)Inserts and shifts; the size grows by one.
get(i)Reads the element without changing it.
replaceAll(op)Replaces every element with a computed value.
listIterator()Its set() replaces the element just returned while looping.

Java Examples

Example 1 — Fix a Typo in a List

Replace a misspelled word and keep the word that was replaced.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListSetDemo {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banan", "cherry"));

        String old = fruits.set(1, "banana");
        System.out.println("replaced: " + old);
        System.out.println(fruits + " size=" + fruits.size());
    }
}

How It Works

  1. A typo at index 1. The second element is spelled "banan".
  2. Swap it in place. set(1, "banana") writes the corrected word into the same slot.
  3. Old value back. The method returns what it replaced, so old holds "banan".
  4. No growth. The size is still 3, because set replaces instead of inserting.

Example 2 — set() vs add() at the Same Index

Run set(1, ...) and add(1, ...) on twin lists.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListSetVsAdd {
    public static void main(String[] args) {
        List<String> a = new ArrayList<>(Arrays.asList("x", "y", "z"));
        List<String> b = new ArrayList<>(Arrays.asList("x", "y", "z"));

        a.set(1, "NEW");
        b.add(1, "NEW");

        System.out.println("set: " + a + " size=" + a.size());
        System.out.println("add: " + b + " size=" + b.size());
    }
}

How It Works

  1. Twin lists. a and b both start as [x, y, z].
  2. set overwrites. In a, "y" is gone, replaced by "NEW"; the size stays 3.
  3. add inserts. In b, "NEW" goes in at index 1 and "y" moves to index 2, so the size becomes 4.
  4. Rule of thumb. Use set to change a value that is already there and add to put in a new one.

Example 3 — Double Every Score with get() and set()

Read, compute, and write back each element, then try to set an index that does not exist.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListSetLoop {
    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>(Arrays.asList(5, 8, 12));

        for (int i = 0; i < scores.size(); i++) {
            scores.set(i, scores.get(i) * 2);
        }
        System.out.println("doubled: " + scores);

        try {
            scores.set(3, 0);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("set(3, 0) failed: only indexes 0-2 exist");
        }
    }
}

How It Works

  1. Read, compute, write. For each index, get(i) reads the score, * 2 doubles it, and set(i, ...) stores the result back.
  2. Boxing round trip. The Integer is unboxed for the multiplication, and the result is boxed again when it is stored.
  3. Safe during the loop. set does not change the size, so the loop visits every element exactly once.
  4. 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.

Next: size()

Count the elements in the list.

size() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful