LinkedList iterator
In this chapter you will learn:
Get iterator from LinkedList
Iterator<E> iterator()
Returns an iterator over the elements.
ListIterator<E> listIterator(int index)
Returns a list-iterator starting at the specified position in the list.
import java.util.Iterator;
import java.util.LinkedList;
// ja v a2s . c o m
public class Main{
public static void main(String args[]) {
LinkedList<String> ll = new LinkedList<String>();
ll.add("A");
ll.add("ja v a2s.com");
ll.addLast("B");
ll.add("C");
Iterator<String> itr = ll.iterator();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
}
}
The output:
Get List Iterator from a LinkedList
The following code calls listIterator from LinkedList
and passes in
an offset. It returns a ListIterator which contains the elements starting
from the offset.
import java.util.LinkedList;
import java.util.ListIterator;
/*from j a v a 2s . c o m*/
public class Main{
public static void main(String args[]) {
LinkedList<String> ll = new LinkedList<String>();
ll.add("A");
ll.add("ja v a2s.com");
ll.addLast("B");
ll.add("C");
ListIterator<String> itr = ll.listIterator(1);
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections