Thursday 26 July 2012

Add an element to specified index of Java LinkedList Example



This Java example shows how to add an element at specified index of Java LinkedList object using add method.


import java.util.LinkedList;

public class AddElementToSpecifiedIndexLinkedListExample {

 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 add an element at the specified index of LinkedList use void
   * add(int index, Object obj) method. This method inserts the specified
   * element at the specified index in the LinkedList.
   **/
  lList.add(1, "INSERTED ELEMENT");

  /**
   * Please note that add method DOES NOT overwrites the element
   * previously at the specified index in the list. It shifts the elements
   * to right side and increasing the list size by 1.
   **/

  System.out.println("After Insertion. 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
After Insertion. LinkedList contains...
1
INSERTED ELEMENT
2
3

No comments:

Post a Comment