VOOZH about

URL: https://www.geeksforgeeks.org/java/arraylist-set-method-in-java-with-examples/

⇱ Java ArrayList set() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java ArrayList set() Method

Last Updated : 6 Aug, 2025

The set() method of the ArrayList class in Java is used to replace an element at a specified position with a new value. This is very useful when we need to update an existing element in an ArrayList while maintaining the list's structure.

Example 1: Here, we will use the set() method to update an element in an ArrayList.


Output
Before operation: [1, 2, 3, 4, 5]
After operation: [1, 2, 3, 9, 5]
Replaced element: 4

Explanation: In the above example, it replaced an element in an ArrayList and prints both the updated list and the replaced element.

Syntax of ArrayList set() Method

public E set(int index, E element)

Parameters:

  • index: Index of the element to replace.
  • element: Element to be stored at the specified position.

Returns Value: It returns the element that was previously at the specified position.

Exception: IndexOutOfBoundsException: Thrown if the index is out of the valid range (index < 0 or index >= size).

Example 2: Here, this example will show how trying to replace an element at an invalid index results in an exception.


Output
Before operation: [1, 2, 3, 4, 5]
Exception: java.lang.IndexOutOfBoundsException: Index 7 out of bounds for length 5
Comment