List and its Iterator
In this chapter you will learn:
Get Iterator from a List
List stores its elements in a sequence. We can
loop through each element with its index. Another way
of iterating each element is to use the Iterator
.
Iterator
is an interface defined for iterating.
The following three methods returns Iterator over the list.
Iterator<E> iterator()
Returns an iterator over the elements in this list in proper sequence.ListIterator<E> listIterator()
Returns a list iterator over the elements in this list (in proper sequence).ListIterator<E>listIterator(int index)
Returns a list iterator of the elements in this list (in proper sequence), starting at the specified position in this list.
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/* ja v a2 s. co m*/
public class Main {
public static void main(String[] args) {
List list = Collections.nCopies(5, "java2s.com");
System.out.println("List contains, ");
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections