Thursday 26 July 2012

Remove an element from specified index of Java LinkedList Example


This Java Example shows how to remove an element at specified index of java LinkedList object using remove method.


import java.util.LinkedList;

public class RemoveElementFromLinkedListExample {

 public static void main(String[] args) {

  // create an LinkedList object
  LinkedList lList = new LinkedList();

  // Appends the specified element to the end of this list
  lList.add("1");
  lList.add("2");
  lList.add("3");

  System.out.println("LinkedList contains...");

  // display elements of LinkedList
  for (int index = 0; index < lList.size(); index++)
   System.out.println(lList.get(index));

  /*
   * To remove an element from the specified index of LinkedList use
   * Object remove(int index) method. It returns the element that was
   * removed from the LinkedList.
   */

  Object obj = lList.remove(1);
  System.out.println(obj + " is removed from LinkedList");

  System.out.println("Modified LinkedList contains...");

  // display elements of LinkedList
  for (int index = 0; index < lList.size(); index++)
   System.out.println(lList.get(index));

 }
}


The output is:



LinkedList contains...
1
2
3
2 is removed from LinkedList
Modified LinkedList contains...
1
3

No comments:

Post a Comment