Categories

Thursday, 26 July 2012

Remove all elements or clear LinkedList Java example


This java example shows how to remove all elements or clear Java LinkedList using clear method.


import java.util.LinkedList;

public class RemoveAllElementsLinkedListExample {

 public static void main(String[] args) {

  // create LinkedList object

  LinkedList lList = new LinkedList();

  // add elements to LinkedList
  lList.add("1");
  lList.add("2");
  lList.add("3");
  lList.add("4");
  lList.add("5");

  System.out.println("LinkedList contains : " + lList);

  /**
   * To remove all elements of Java LinkedList, use void clear() method.
   * 
   * This method remove all elements from LinkedList object.
   **/

  lList.clear();
  System.out.println("LinkedList now contains : " + lList);

 }
}


The output is:



LinkedList contains : [1, 2, 3, 4, 5]
LinkedList now contains : []

No comments:

Post a Comment