Write a Java program to remove all the elements from a linked list


The Java code provided demonstrates how to remove all elements from a linked list using the clear method.

  • The code defines a class named Remove_AllElements with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a LinkedList object named fru_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Papaya", "Mulberry", "Apple", "Banana", "Cherry", and "Watermelon" are added to fru_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the contents of fru_list before removing all elements.
  • The fru_list.clear() statement is called to remove all elements from fru_list. The clear method is a built-in method in Java that removes all elements from a collection.
  • The System.out.println statement is used to print the contents of fru_list after removing all elements. As a result, an empty list will be printed.
  • The output of the program will be the contents of fru_list printed before and after removing all elements.

Source Code

import java.util.*;
public class Remove_AllElements
{
	public static void main(String[] args)
	{
		LinkedList<String> fru_list = new LinkedList<String>();
		fru_list.add("Papaya");
		fru_list.add("Mulberry");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		fru_list.add("Watermelon");
		System.out.println("Given linked list : " + fru_list);
		fru_list.clear();
		System.out.println("Remove All Element from a Linked list : " + fru_list);
	}
}

Output

Given linked list : [Papaya, Mulberry, Apple, Banana, Cherry, Watermelon]
Remove All Element from a Linked list : []

Example Programs