Write a Java program to Add an element or collection of elements at a specific position of a LinkedList


The code demonstrates various operations on a LinkedList in Java.

  • The Collection_Elements class contains a main method where two LinkedList objects, c1 and c2, are created and populated with string elements using the add, addFirst, and addAll methods.
  • The add method is used to add elements at the end of the c1 linked list. The addFirst method is used to add elements at the head of the c2 linked list.
  • The System.out.println statements are used to print the initial state of the c1 and c2 linked lists.
  • Then, an element is added at index 1 in the c1 linked list using the add method with index as an argument. This will insert the element "White" at index 1, shifting the existing elements to the right.
  • The System.out.println statement is used to print the c1 linked list after adding an element at index 1.
  • Next, elements from the c2 linked list are added at index 4 of the c1 linked list using the addAll method. This will insert all elements from the c2 linked list at index 4 of the c1 linked list, shifting the existing elements to the right.
  • The System.out.println statement is used to print the c1 linked list after adding all elements from the c2 linked list.
  • As a result, the c1 linked list will contain the added elements "White" at index 1 and "Purple", "Red", "Yellow" at index 4, in the order they were added, as demonstrated by the printed output.

Source Code

import java.util.*;
public class Collection_Elements
{
	public static void main(String[] args)
	{
		LinkedList<String> c1 = new LinkedList<String>(); 
		c1.add("Blue");
		c1.add("Green");
		c1.add("Pink");
		c1.add("Black");
		c1.add("Orange");  
		System.out.println(c1);           
		c1.add(1, "White"); //Adding an element at index 1
		System.out.println(c1);
 
		LinkedList<String> c2 = new LinkedList<String>(); 
		c2.addFirst("Purple"); 
		c2.addFirst("Red");
		c2.addFirst("Yellow"); 
		System.out.println(c2); 
 
		c1.addAll(4, c2); //Adding all elements of list1 at index 3 of list  
		System.out.println(c1);
	}
}

Output

[Blue, Green, Pink, Black, Orange]
[Blue, White, Green, Pink, Black, Orange]
[Yellow, Red, Purple]
[Blue, White, Green, Pink, Yellow, Red, Purple, Black, Orange]

Example Programs