![]() |
VOOZH | about |
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.
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.
public E set(int index, E element)
Parameters:
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.
Before operation: [1, 2, 3, 4, 5] Exception: java.lang.IndexOutOfBoundsException: Index 7 out of bounds for length 5