To replace an element in Java ArrayList, set() method of java.util. 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
when the index is out of range
i.e, index < 0 or index >= size()
Java
// Java program to demonstrate set() // method of ArrayList import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { try { ArrayList<String> list = new ArrayList<>(); // adding elements to the list list.add( "A" ); list.add( "B" ); list.add( "C" ); list.add( "D" ); System.out.println(list); // 2 is the index of the element "B". //"B" will be replaced by "E" list.set( 2 , "E" ); System.out.println(list); list.set( 6 , "z" ); } catch (Exception e) { System.out.println(e); } } } |
[A, B, C, D] [A, B, E, D] java.lang.IndexOutOfBoundsException: Index 6 out of bounds for length 4
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.