To replace an element in Java ArrayList, set() method of java.util. An ArrayList class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element. The index of an ArrayList is zero-based. So, to replace the first element, 0 should be the index passed as a parameter.
Declaration:
public Object set(int index, Object element)
Return Value: The element which is at the specified index
Exception Throws: IndexOutOfBoundsException
This occurs when the index is out of range.
index < 0 or index >= size()
Implementation:
Here we will be proposing out 2 examples wherein one of them we will be setting the index within bound and in the other, we will be setting the index out of bounds.
Example 1: Where Index is Within Bound
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args) {
try {
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
System.out.println(list);
list.set(2, "E");
System.out.println(list);
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output
[A, B, C, D]
[A, B, E, D]
Example 2: Where Index is Out of Bound
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args) {
try {
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");ÃĨ
list.add("C");
list.add("D");
System.out.println(list);
list.set(6);
System.out.println(list);
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:

Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
27 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...