Write a Java program to test an linked list is empty or not
The Java code provided demonstrates how to check if a linked list is empty or not, and how to remove all elements from a linked list.
- The code defines a class named LinkedList_EmptyNot 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", etc., are added to fru_list using the add method, which appends the elements to the end of the list.
- The System.out.println statements are used to print the initial contents of fru_list before any modifications.
- The fru_list.isEmpty() method is called to check if fru_list is empty or not. This method returns true if the list is empty (contains no elements), and false otherwise. The result of this check is printed using a System.out.println statement.
- The fru_list.removeAll(fru_list) method is called to remove all elements from fru_list. This method removes all occurrences of the elements in the specified collection from the list.
- Another System.out.println statement is used to print the contents of fru_list after removing all elements from it.
- Finally, the fru_list.isEmpty() method is called again to check if fru_list is empty or not after removing all elements, and the result is printed using a System.out.println statement.
- The output of the program will be the initial contents of fru_list printed on the first line, followed by the result of the fru_list.isEmpty() check before and after removing all elements from fru_list printed on the next two lines, respectively.
Source Code
import java.util.LinkedList;
import java.util.Collections;
public class LinkedList_EmptyNot
{
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);
System.out.println("Check the above linked list is empty or not : "+fru_list.isEmpty());
fru_list.removeAll(fru_list);
System.out.println("After Remove all Elements in Linked list : "+fru_list);
System.out.println("Check the above linked list is Empty or Not : "+fru_list.isEmpty());
}
}
Output
Given linked list : [Papaya, Mulberry, Apple, Banana, Cherry, Watermelon]
Check the above linked list is empty or not : false
After Remove all Elements in Linked list : []
Check the above linked list is Empty or Not : true