Java
ArrayList
Replace method
Programming
Index manipulation

Java ArrayList replace at specific index

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

To replace an element at a specific position in a Java ArrayList, use the set method. It is the right tool when the index already exists and you want to overwrite the old value without changing the size of the list.

The set Method

ArrayList exposes this method:

java
E set(int index, E element)

It performs three things:

  1. checks that the index is valid,
  2. writes the new element into that slot,
  3. returns the old element that used to be there.

A simple example looks like this:

java
1import java.util.ArrayList;
2import java.util.Arrays;
3
4public class ReplaceAtIndex {
5    public static void main(String[] args) {
6        ArrayList<String> colors = new ArrayList<>(Arrays.asList(
7            "red", "green", "blue"
8        ));
9
10        String previous = colors.set(1, "yellow");
11
12        System.out.println(previous);
13        System.out.println(colors);
14    }
15}

Output:

text
green
[red, yellow, blue]

The list still has three elements. Only the value at index 1 changed.

set Is Not the Same as add

This distinction matters a lot.

  • 'set(index, value) replaces an existing element.'
  • 'add(value) appends a new element.'
  • 'add(index, value) inserts a new element and shifts later elements.'

If you use add(index, value) when you meant to replace, the list grows and the elements move, which may quietly break downstream logic.

java
1ArrayList<String> names = new ArrayList<>(Arrays.asList("Ava", "Leo", "Mina"));
2
3names.add(1, "Kai");
4System.out.println(names);

Output:

text
[Ava, Kai, Leo, Mina]

That is insertion, not replacement.

The Index Must Already Exist

A common beginner error is trying to use set on an index that has not been created yet.

java
ArrayList<String> items = new ArrayList<>();
// items.set(0, "book");

That throws IndexOutOfBoundsException because the list is empty. set cannot create new positions. The valid index range is from 0 to size() - 1.

If you are building the list for the first time, use add. Use set only after the list already contains a value at that position.

Safe Replacement With Dynamic Input

If the index comes from user input, a calculation, or another data source, validate it before replacing.

java
1import java.util.ArrayList;
2import java.util.Arrays;
3
4public class SafeSetExample {
5    public static void main(String[] args) {
6        ArrayList<String> names = new ArrayList<>(Arrays.asList("Ava", "Leo", "Mina"));
7        int index = 2;
8
9        if (index >= 0 && index < names.size()) {
10            names.set(index, "Nora");
11        }
12
13        System.out.println(names);
14    }
15}

That guard is simple, but it prevents a large class of runtime errors.

Why the Return Value Can Be Useful

Many code examples ignore the return value from set, but it can be helpful for logging, comparisons, or update auditing.

java
String oldName = names.set(0, "Eli");
System.out.println("Replaced " + oldName + " with Eli");

If you need to know what changed, the old value is already available.

Performance Characteristics

For an ArrayList, replacement at a known valid index is efficient because the underlying structure is an array. Java can directly overwrite that slot, so the operation is generally constant time.

That efficiency is another reason to keep the distinction clear:

  • 'set is direct replacement,'
  • 'add(index, value) requires shifting later elements,'
  • 'remove(index) shifts elements in the other direction.'

Using the right method makes intent clearer and performance more predictable.

Common Pitfalls

A common mistake is calling set on an empty list or on an index equal to size(). That fails because the slot does not exist yet.

Another issue is confusing replacement with insertion. If the code unexpectedly changes list length, check whether add(index, value) was used instead of set.

Developers also sometimes skip bounds checks when the index is derived from outside input. That makes a simple collection update depend on fragile assumptions.

Summary

  • Use ArrayList#set when you want to replace an existing element at a known index.
  • 'set does not grow the list or shift elements.'
  • The index must already be within the current bounds of the list.
  • Use add for insertion and set for replacement.
  • The method returns the old value, which can be useful for logging or comparison.

Course illustration
Course illustration

All Rights Reserved.