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:
IndexOutOfBoundsExceptionis thrown when the index is less than0or greater than or equal to the size of the ArrayList.
Example: Replace an Element in ArrayList
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
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
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:

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.