Home » Java programming language

Java LinkedList void clear() method with Example

Java LinkedList void clear() method: Here, we are going to learn about the void clear() method of LinkedList class with its syntax and example.
Submitted by Preeti Jain, on June 17, 2019

LinkedList void clear() method

  • This method is available in package java.util.Collection and here, Collection is an interface.
  • This method is declared in interface Collection and it is implemented by the class LinkedList.
  • This method is used to remove all the elements from the linked list.
  • This method is used to remove or clear all the elements from the linked list and not delete the linked list.

Syntax:

    void  clear(){
    }

Parameter(s):

This method does not accept any parameter.

Return value:

The return type of this method is void that means this method returns nothing after execution.

Java program to demonstrate example of LinkedList clear() method

import java.util.LinkedList;

public class LinkList {
 public static void main(String[] args) {
  LinkedList list = new LinkedList();
  // use add() method to add few elements in the list 
  list.add(10);
  list.add(20);
  list.add(30);
  list.add(40);
  list.add(50);

  //  Current list Output
  System.out.println("The Current list is:" + list);

  // Clear or remove all the elements from the list 
  list.clear();

  //  New list Output 
  System.out.println("The new List is:" + list);
 }
}

Output

D:\Programs>javac LinkList.java

D:\Programs>java LinkList
The Current list is:[10, 20, 30, 40, 50]
The new List is:[]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.