Write a Java program to Insert more than one element at a particular position of an ArrayList


This program demonstrates how to insert more than one element at a particular position of an ArrayList in Java.

  • We create two ArrayLists, b1_list and b2_list, and add some elements to them using the add() method.
  • We then print the elements of both ArrayLists using the println() method.
  • We use the addAll() method to insert all the elements of b2_list at index 3 of b1_list.
  • Finally, we print the elements of b1_list to verify that the elements of b2_list have been inserted at index 3.

Source Code

import java.util.ArrayList;
public class InsertElement_MoreThenOne
{
    public static void main(String[] args)
    {   
		ArrayList<String> b1_list = new ArrayList<String>();
		b1_list.add("Java");
		b1_list.add("Cpp");
		b1_list.add("Python");
		b1_list.add("Php");
		b1_list.add("Ruby");         
		System.out.println("ArrayList 1 : "+b1_list);
 
		ArrayList<String> b2_list = new ArrayList<String>();
		b2_list.add("C");
		b2_list.add("CSS");
		b2_list.add("HTML");
		b2_list.add("MySql"); 
		System.out.println("ArrayList 2 : "+b2_list);
 
		//Inserting all elements of b2_list at index 3 of b1_list         
		b1_list.addAll(3, b2_list);
 
		System.out.println("Insert more than one element at a particular position of an ArrayList..");
		System.out.println(b1_list);
    }
}

Output

ArrayList 1 : [Java, Cpp, Python, Php, Ruby]
ArrayList 2 : [C, CSS, HTML, MySql]
Insert more than one element at a particular position of an ArrayList..
[Java, Cpp, Python, C, CSS, HTML, MySql, Php, Ruby]

Example Programs