ArrayList.add() method is employed to feature a component at particular index in Java ArrayList.
Syntax:
public void add(int index, Object element) ;
Parameters:
Exception:
For a list of string list=[A,B,C] list.add(1,”D”); list.add(2,”E”); list=[A,D,E,B,C] For a list of integers LIST=[1,2,3] list.add(2,4); list=[1,2,4,3]
Implementation:
// Adding an Element at Particular // Index in Java ArrayList import java.io.*; import java.util.ArrayList; class GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList ArrayList list = new ArrayList<>(); // Adding elements to ArrayList // using add method for String ArrayList list.add("A"); list.add("B"); list.add("C"); /* Index is zero based */ // 3 gets added to the 1st position list.add(1, "D"); // 4 gets added to the 2nd(position) list.add(2, "E"); // Displaying elements in ArrayList System.out.println(list); } }
Output
[A, D, E, B, C]