Write a Java program to Retrieve and remove and only retrieve an element from specific position of a LinkedList


The code demonstrates how to retrieve and remove elements from a specific index in a LinkedList in Java. The Retrieve_Remove class contains a main method where a LinkedList object named list is created and populated with string elements using the add method.

The System.out.println statements are used to print the initial state of the list linked list. Then, the following methods are used to retrieve and remove an element from the list linked list at a specific index:

  • remove(index) : Retrieves and removes the element at the specified index from the list linked list. The removed element is returned. Throws IndexOutOfBoundsException if the index is out of range (index < 0 || index >= size of list).
  • get(index) : Retrieves the element at the specified index from the list linked list without removing it. Throws IndexOutOfBoundsException if the index is out of range (index < 0 || index >= size of list).

The System.out.println statements are used to print the retrieved and removed element, as well as the updated state of the list linked list after the removal operation.

As a result, the element at index 4 of the list linked list will be retrieved and removed using the remove(4) method, and its value will be printed. Then, the updated state of the list linked list after the removal operation will be printed using the System.out.println(list) statement. Finally, the element at index 4 of the list linked list will be retrieved using the get(4) method, and its value will be printed.

Source Code

import java.util.*;
public class Retrieve_Remove
{
	public static void main(String[] args)
	{
		LinkedList<String> list = new LinkedList<String>(); 
		list.add("C"); 
		list.add("JAVA"); 
		list.add("PYTHON"); 
		list.add("CPP"); 
		list.add("Ruby");
		list.add("C#.NET"); 
		System.out.println(list);
 
		//Retrieving and removing an element at index 4 
		System.out.println(list.remove(4));
		System.out.println(list); 
 
		//Only retrieving an element at index 4 
		System.out.println(list.get(4));
	}
}

Output

[C, JAVA, PYTHON, CPP, Ruby, C#.NET]
Ruby
[C, JAVA, PYTHON, CPP, C#.NET]
C#.NET

Example Programs