Java ArrayList set() Method
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.
// Update an element in an ArrayList
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList and
// add elements
ArrayList<Integer> n = new ArrayList<>();
n.add(1);
n.add(2);
n.add(3);
n.add(4);
n.add(5);
// Print the original ArrayList
System.out.println("Before operation: " + n);
// Replace element at
// index 3 with 9
int r = n.set(3, 9);
System.out.println("After operation: " + n);
System.out.println("Replaced element: " + r);
}
}
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.
// Handling IndexOutOfBoundsException
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
try {
// Create an ArrayList and add elements
ArrayList<Integer> n = new ArrayList<>();
n.add(1);
n.add(2);
n.add(3);
n.add(4);
n.add(5);
// Print the original ArrayList
System.out.println("Before operation: " + n);
// Attempt to replace an element at an invalid index
n.set(7, 9);
} catch (IndexOutOfBoundsException e) {
// Handle the exception
System.out.println("Exception: " + e);
}
}
}
Output
Before operation: [1, 2, 3, 4, 5] Exception: java.lang.IndexOutOfBoundsException: Index 7 out of bounds for length 5