Organizational Research By

Surprising Reserch Topic

How to loop LinkedList in Java


In the last tutorial we discussed LinkedList and it‚Äôs methods with example. Here we will see how to loop/iterate a LinkedList. There are four ways in which a LinkedList can be iterated ‚Äď

For loop
Advanced For loop
Iterator
While Loop
Example:
In this example we have a LinkedList of String Type and we are looping through it using all the four mentioned methods.

package beginnersbook.com;
import java.util.*;

public class LinkedListExample {

   public static void main(String args[]) {
      /*LinkedList declaration*/
      LinkedList linkedlist=new LinkedList();
      linkedlist.add("Apple");
      linkedlist.add("Orange");
      linkedlist.add("Mango");

      /*for loop*/
      System.out.println("**For loop**");
      for(int num=0; num       {
          System.out.println(linkedlist.get(num));
      }

      /*Advanced for loop*/
      System.out.println("**Advanced For loop**");
      for(String str: linkedlist)
      {
          System.out.println(str);
      }

      /*Using Iterator*/
      System.out.println("**Iterator**");
      Iterator i = linkedlist.iterator();
      while (i.hasNext()) {
      System.out.println(i.next());
      }

      /* Using While Loop*/
      System.out.println("**While Loop**");
      int num = 0;
      while (linkedlist.size() > num) {
      System.out.println(linkedlist.get(num));
      num++;
      }

   }
}
Output:

**For loop**
Apple
Orange
Mango
**Advanced For loop**
Apple
Orange
Mango
**Iterator**
Apple
Orange
Mango
**While Loop**
Apple
Orange
Mango
asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
87 views



Related Hot Questions



Government Jobs Opening


...