Use ArrayList.add[int index, E element] method to add element to specific index of ArrayList. To replace element at specified index, use ArrayList.set[int index, E element] method.
1. ArrayList.add[int index, E element] Add element at specified index
This method inserts the specified element E at the specified position in this list. It shifts the element currently at that position [if any] and any subsequent elements to the right [will add one to their indices].
Index start with 0.
public class ArrayListExample { public static void main[String[] args] { ArrayList namesList = new ArrayList[Arrays.asList[ "alex", "brian", "charles"] ]; System.out.println[namesList]; //list size is 3 //Add element at 0 index namesList.add[0, "Lokesh"]; System.out.println[namesList]; //list size is 4 } }Program output.
[alex, brian, charles] [Lokesh, alex, brian, charles]2. ArrayList.set[int index, E element] Replace element at specified index
This method replaces the specified element E at the specified position in this list. As this method replaces the element, the list size does not change.
Index start with 0.
Java program to update an arraylist element. It replace element at specified index of arraylist.
public class ArrayListExample { public static void main[String[] args] { ArrayList namesList = new ArrayList[Arrays.asList[ "alex", "brian", "charles"] ]; System.out.println[namesList]; //list size is 3 //Add element at 0 index namesList.set[0, "Lokesh"]; System.out.println[namesList]; //list size is 3 } }Program output.
[alex, brian, charles] [Lokesh, brian, charles]3. Replace element in arraylist while iterating
Do not use iterator if you plan to modify the arraylist during iteration. Use standard for loop, and keep track of index position to check the current element. Then use this index to set the new element.
Java program to search and replace an element in an ArrayList.
public class ArrayListExample { public static void main[String[] args] { ArrayList namesList = new ArrayList[Arrays.asList[ "alex", "brian", "charles"] ]; System.out.println[namesList]; //Replace item while iterating for[int i=0; i < namesList.size[]; i++] { if[namesList.get[i].equalsIgnoreCase["brian"]] { namesList.set[i, "Lokesh"]; } } System.out.println[namesList]; } }Program output.
[alex, brian, charles] [alex, Lokesh, charles]Happy Learning !!
Read More:
A Guide to Java ArrayList
ArrayList Java Docs
Was this post helpful?
Further Reading:
- Arraylist lastIndexOf[] Get last index of element in arraylist in Java
Learn to get last index of element in arraylist in Java using Arraylist.lastIndexOf[] method. It returns the last occurrence of...
- ArrayList get[] Getting Element at Index
Learn how to get the element from an ArrayList. We will be using ArrayList.get[] method to get the object at...
- Arraylist indexOf[] Get index of element in arraylist
Learn how to get the index of first occurrence of a element in the ArrayList. We will be using ArrayList.indexOf[]...