In order to adding element to arraylist at specific position we can use ArrayList add(index , element) method . This method Inserts the given element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Syntax :
public void add(int index, E element) {
}
- Parameters:
index – index at which the specified element is to be inserted
element – element to be inserted - Exception : It throws following exception
IndexOutOfBoundsException – if the index is out of range (index < 0 || index > size())
Now will see Java ArrayList add(index , element ) Example
import java.util.ArrayList;
public class AddElement {
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
// add element in arraylist
arr.add("c");
arr.add("php");
arr.add("html");
arr.add("java");
arr.add("delhi");
arr.add("INDIA");
// print arraylist
System.out.println("arrayList is = " + arr);
/*
* Inserts the specified element at the
* specified position in this list
* . Shifts the element currently at that position
* (if any) and any subsequent elements to the right
*/
arr.add(1,"javascript");
// print arraylist
System.out.println("after insert arrayList is = " + arr);
}
}
Output:
arrayList is = [c, php, html, java, delhi, INDIA]
after insert arrayList is = [c, javascript, php, html, java, delhi, INDIA]