how to iterate over a LinkedList using the Collections API
Previous | Home | Next |
In this example we shall see how can we iterate over a LinkedList using the Iterator.
In this example we have created a class CollectionExample. For using LinkedList we have
to import the java.util package.
In this example we have used the Iterator interface for iterating through the LinkedList that we have created. For using the iteratror firstly we will invoke the iterator on the LinkedList object, then we iterate through the list by using the next() method on the iterator.
In this example we have created a LinkedList named list and then added some elements to it by using the add() method on the list. Then we have invoked the Iterator on the LinkedList object list and iterate till the iterator see's there is some other element in the list. The following code in the given example invokes the iterator on the list :ListIterator<Object> ltr=list.listIterator();
while(ltr.hasNext())
{
System.out.println(ltr.next());
}
package r4r.co.in;
import java.util.*;
import java.util.Iterator;
import java.util.List;
import java.util.Collection;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
LinkedList<Object> list=new LinkedList<Object>(); // creating a LinkedList of Object type elements
list.add(1); // adding integer values to the LinkedList
list.add(2);
list.add("r4r"); // adding String values to the LinkedList
list.add("shashi");
list.add("s/w engineer");
System.out.println("The contents of the list are as follows: ");
ListIterator<Object> ltr=list.listIterator(); // Invoking the ListIterator on the list for iterating through the list
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the contents of the list
}
}
}
The output will be displayed as:
The contents of the list are as follows:
1
2
r4r
shashi
s/w engineer
Previous | Home | Next |