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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- ArrayList clone() method in Java with Examples
- ArrayList removeAll() method in Java with Examples
- ArrayList get(index) method in Java with examples
- ArrayList toArray() method in Java with Examples
- ArrayList subList() method in Java with Examples
- ArrayList ensureCapacity() method in Java with Examples
- ArrayList listIterator() method in Java with Examples
- ArrayList iterator() method in Java with Examples
- ArrayList size() method in Java with Examples
- Arraylist removeRange() in Java with examples
- ArrayList clear() in Java with examples
- ArrayList and LinkedList remove() methods in Java with Examples
- Java.util.ArrayList.addall() method in Java
- ArrayList retainAll() method in Java
- ArrayList removeIf() method in Java
- ArrayList forEach() method in Java
- ArrayList spliterator() method in Java
- Java.util.ArrayList.add() Method in Java
- ArrayList of ArrayList in Java
- Java.util.Arraylist.indexOf() in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.