beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Remove all elements from LinkedList example

By Chaitanya Singh | Filed Under: Java Collections

In this example we will see how to remove all the elements from LinkedList. We will be using clear() method of LinkedList class to do this. Method definition and description are as follows:

public void clear(): Removes all of the elements from this list. The list will be empty after this call returns.

Example

In this example we have a LinkedList of String type that has 5 elements. We are calling clear() method and displaying the LinkedList elements before and after calling the clear() method.

import java.util.LinkedList;
public class RemoveAllExample {
 
 public static void main(String[] args) {
 
    // Create a LinkedList
    LinkedList<String> linkedlist = new LinkedList<String>();
 
    // Add elements to LinkedList
    linkedlist.add("Item1");
    linkedlist.add("Item2");
    linkedlist.add("Item3");
    linkedlist.add("Item4");
    linkedlist.add("Item5");
 
    // Displaying Elements before remove
    System.out.println("Before clear():");
    for(String str: linkedlist){
       System.out.println(str);
    }
 
    // Removing all the elements from LinkedList
    linkedlist.clear();
 
    // LinkedList elements after remove
    System.out.println("After clear():");
    for(String str2: linkedlist){
       System.out.println(str2);
    }
 }
}

Output:

Before clear():
Item1
Item2
Item3
Item4
Item5
After clear():

Enjoyed this post? Try these related posts

  1. Java – Convert Vector to ArrayList example
  2. How to sort HashMap in Java by Keys and Values
  3. Get size of Hashtable example in Java
  4. Remove Key-value mapping from TreeMap example
  5. Java – Remove specific elements from LinkedList example
  6. How to iterate TreeMap in reverse order in Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap