Thursday 26 July 2012

Replace an element at specified index of Java LinkedList Example


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


import java.util.LinkedList;

public class ReplaceElementAtSpecifiedIndexLinkedListExample {

 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 replace an element at the specified index of LinkedList use Object
   * set(int index, Object obj) method. This method replaces the specified
   * element at the specified index in the LinkedList and returns the
   * element previously at the specified position.
   */
  Object replaced = lList.set(1, "REPLACED ELEMENT");

  System.out.println(replaced + " is replaced with new element.");

  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 replaced with new element.
Modified LinkedList contains...
1
REPLACED ELEMENT
3

No comments:

Post a Comment