Write a Java program to insert an element at a particular position of an ArrayList


This code demonstrates how to insert elements at a particular position in an ArrayList in Java. The ArrayList is first created with some initial elements, and then two new elements are inserted at positions 1 and 5 using the add() method with the index parameter. Here's how the code works:

  • Create an ArrayList called col_list and add some elements to it using the add() method.
  • Print the original ArrayList.
  • Use the add() method to insert the element "White" at position 1 and the element "Yellow" at position 5.
  • Print the updated ArrayList.

Source Code

import java.util.ArrayList;
public class InsertParticular_Position
{
    public static void main(String[] args)
    {
		ArrayList<String> col_list = new ArrayList<String>();
		col_list.add("Blue");
		col_list.add("Green");
		col_list.add("Pink");
		col_list.add("Black");
		col_list.add("Red");
		col_list.add("orange");
		System.out.println("Given ArrayList : "+col_list);
 
		//Insert "White" at index 1 
		col_list.add(1, "White");
 
		//Insert "Yellow" at index 5 
		col_list.add(5, "Yellow");
 
		System.out.println("Insert an Element at a Particular Position of an ArrayList..");
		System.out.println(col_list);
    }
}

Output

Given ArrayList : [Blue, Green, Pink, Black, Red, orange]
Insert an Element at a Particular Position of an ArrayList..
[Blue, White, Green, Pink, Black, Yellow, Red, orange]

Example Programs