Write a Java program to insert some elements at the specified position into a linked list


This Java code demonstrates how to use a LinkedList to add multiple elements at a specific position in the list using the addAll method.

  • First, the code imports the java.util.LinkedList class, which is used to create and manipulate linked lists in Java.
  • The InsertSome_Elements class is defined with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a new LinkedList object named fru_list is created with a type parameter of String, which means it will store strings as its elements.
  • Several strings, such as "Mulberry", "Guava", "Papaya", etc., are added to the fru_list using the add method, which appends the elements to the end of the list.
  • The initial contents of the fru_list are printed using System.out.println statement, which displays the list as: "Given linked list: [Mulberry, Guava, Papaya, Apple, Banana, Cherry]".
  • Next, a new LinkedList object named new_fru_list is created with a type parameter of String, which will store strings as its elements. This list contains two strings, "Watermelon" and "Pineapple".
  • The addAll method is called on fru_list with two arguments: the index at which the new elements should be inserted, which is 3, and the collection of elements to be inserted, which is new_fru_list. This inserts the elements of new_fru_list at the fourth position in the fru_list, shifting the existing elements to the right.
  • Finally, the updated contents of the fru_list are printed again using System.out.println statement, which displays the list after inserting the elements of new_fru_list as: "Linked List : [Mulberry, Guava, Papaya, Watermelon, Pineapple, Apple, Banana, Cherry]".

Source Code

import java.util.LinkedList;
public class InsertSome_Elements
{
	public static void main(String[] args)
	{
		LinkedList <String> fru_list = new LinkedList <String> ();
		fru_list.add("Mulberry");
		fru_list.add("Guava");
		fru_list.add("Papaya");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		System.out.println("Given linked list:" + fru_list);
		LinkedList <String> new_fru_list = new LinkedList <String> ();
		new_fru_list.add("Watermelon");
		new_fru_list.add("Pineapple");
		fru_list.addAll(3, new_fru_list);
		System.out.println("Linked List :" + fru_list);
	}
}

Output

Given linked list:[Mulberry, Guava, Papaya, Apple, Banana, Cherry]
Linked List :[Mulberry, Guava, Papaya, Watermelon, Pineapple, Apple, Banana, Cherry]

Example Programs