Thursday 26 July 2012

Display all elements in a Java LinkedList Example


This java example shows how to display all elements in a Java LinkedList object using get method,Iterator , ListIterator and for-each loop.


import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

public class DisplayAllElementsInLinkedListExample {

 public static void main(String[] args) {

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

  // Add elements to Arraylist

  lList.add("1");
  lList.add("2");
  lList.add("3");

  System.out.println("Linkedlist contains : ");

  System.out.println("Display elements using get method.");

  for (int i = 0; i < lList.size(); i++)
   System.out.println(lList.get(i));

  System.out.println("Display elements using Iterator.");

  Iterator i = lList.iterator();
  while (i.hasNext()) {
   System.out.println(i.next());
  }
  System.out.println("Display elements using ListIterator.");

  ListIterator listi = lList.listIterator();

  while (listi.hasNext()) {
   System.out.println(listi.next());
  }

  System.out
    .println("Display elements using for-each loop(available since jdk1.5)");

  for (Object e : lList) {

   System.out.println(e);
  }

 }

}


The output is:



Linkedlist contains :
Display elements using get method.
1
2
3
Display elements using Iterator.
1
2
3
Display elements using ListIterator.
1
2
3
Display elements using for-each loop(available since jdk1.5)
1
2
3

1 comment:

  1. visit java linkedlist examples

    http://www.javaproficiency.com/2015/05/java-linkedlist-examples.html

    ReplyDelete