How to Browse a LinkedList in Java
In the previous tutorial, We saw a class LinkedList and its constructors and methods for example. In this tutorial, we'll see how to navigate through a LinkedList.
LinkedList can be processed with one of 4 loops:
References:
How to Iterate through LinkedList Instance in Java?
LinkedList can be processed with one of 4 loops:
- Loop for
- Loop for advanced or foreach
- Loop while
- Loop while+Iterator
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
public class parcours {
public static void main(String[] args) {
LinkedList< String> llist = new LinkedList< String> ();
llist.add("smartphone");
llist.add("tablet");
llist.add("phablet");
/*For Loop*/
System.out.println("For Loop");
for(int i = 0 ; i < llist.size(); i++)
System.out.println(llist.get(i));
/*Advanced For Loop*/
System.out.println("\nAdvanced For Loop");
for(String n: llist)
System.out.println(n);
/*Loop While*/
System.out.println("\nLoop while");
int i = 0;
while(i< llist.size()){
System.out.println(llist.get(i));
i++;
}
/*While + Iterator Loop*/
System.out.println("\nIterator Loop");
Iterator< String> it = llist.iterator();
while(it.hasNext())
System.out.println(it.next());
}
}
Output:
Loop forIterator is obtained from the iterator() from LinkedList. You can iterate through the elements of iterator with the while loop that takes place as long as there are still elements. hasNext() returns true if there are elements to browse otherwise false. iterator.next() displays the following item in the LinkedList.
smartphone
tablet
phablet
Advanced for loop
smartphone
tablet
phablet
Loop while< br />smartphone
tablet
phablet
Loop Iterator
smartphone
tablet
phablet
References:
How to Iterate through LinkedList Instance in Java?