ArrayList set() method in Java with Examples
The set() method of java.util.ArrayList class is used to replace the element at the specified position in this list with the specified element.
public E set(int index, E element)
Parameters: This method takes the following argument as a parameter.
- index- index of the element to replace
- element- element to be stored at the specified position
Returns Value: This method returns the element previously at the specified position.
Exception: This method throws IndexOutOfBoundsException if the index is not within the size range of the ArrayList.
Below are the examples to illustrate the set() method.
Before operation : [1, 2, 3, 4, 5] After operation : [1, 2, 3, 30, 5] Replaced element : 4
Example 2: For IndexOutOfBoundsException
Before operation : [1, 2, 3, 4, 5] Trying to Replace the element at (index > Capacity) Exception thrown : java.lang.IndexOutOfBoundsException: Index: 7, Size: 5
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.