Replace an Element in Java ArrayList

Last Updated : 1 Sep, 2026

The set() method of the ArrayList class in Java is used to replace an existing element at a specified index. Since ArrayList uses zero-based indexing, the first element is at index 0.

  • set(index, element) replaces the element already present at the specified index.
  • If the index is outside the valid range, Java throws an IndexOutOfBoundsException.

Using set() Method

The set() method takes two arguments: the index of the element to be replaced and the new element.

Syntax

list.set(index, element);

Exception:IndexOutOfBoundsException is thrown when the index is less than 0 or greater than or equal to the size of the ArrayList.

Example: Replace an Element in ArrayList

Java
import java.util.ArrayList;

class ReplaceElement {

    public static void main(String[] args)
    {

        ArrayList<String> list = new ArrayList<>();

        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");

        System.out.println("Original ArrayList: " + list);

        // Replace the element at index 2
        list.set(2, "E");

        System.out.println("Modified ArrayList: " + list);
    }
}

Output
Original ArrayList: [A, B, C, D]
Modified ArrayList: [A, B, E, D]

Explanation: The ArrayList contains "C" at index 2. The statement list.set(2, "E") replaces "C" with "E". The size of the ArrayList remains unchanged.

Example: Replace an Element at a Different Index

Java
import java.util.ArrayList;

class ReplaceElement {

    public static void main(String[] args)
    {

        ArrayList<String> cities = new ArrayList<>();

        cities.add("Delhi");
        cities.add("Mumbai");
        cities.add("Chennai");
        cities.add("Kolkata");

        System.out.println("Original ArrayList: " + cities);

        // Replace the element at index 1
        String oldElement = cities.set(1, "Pune");

        System.out.println("Replaced Element: " + oldElement);
        System.out.println("Modified ArrayList: " + cities);
    }
}

Output
Original ArrayList: [Delhi, Mumbai, Chennai, Kolkata]
Replaced Element: Mumbai
Modified ArrayList: [Delhi, Pune, Chennai, Kolkata]

Explanation: The element at index 1 is "Mumbai". The set() method replaces it with "Pune" and returns the old element "Mumbai".

Example: Index Out of Bounds

Java
import java.util.ArrayList;

class ReplaceElementError {

    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();

        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");

        // Index 6 does not exist
        list.set(6, "X");

        System.out.println(list);
    }
}

Output:

Output
Output showing IndexOutOfBoundsException for an invalid ArrayList index.

Explanation: The ArrayList contains four elements, so its valid indexes are 0 to 3. Since index 6 is outside this range, the set() method throws an IndexOutOfBoundsException.

Comment