A Java iterator spits out a collection's values, one after another. To obtain a value from the collection, you call the iterator's next method. To find out whether the collection has any more values in it, you call the iterator's hasNext method. The code below uses an iterator to display people's names.

Here’s some code for iterating through a collection.

import static java.lang.System.out;

import java.util.Iterator;

import java.util.Scanner;

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

public class ShowNames {

public static void main(String args[]) throws IOException {

ArrayList<String> people = new ArrayList<>();

Scanner diskScanner = new Scanner(new File("names.txt"));

while (diskScanner.hasNext()) {




people.add(2, "Jim Newton");

<strong>Iterator<String> iterator = people.iterator();</strong>

<strong>while (iterator.hasNext()) {</strong>






You can replace the enhanced for with the boldface code above. When you do, you get the same output as before, The first boldface line of code creates an iterator from the people collection. The second and third lines call the iterator's hasNext and next methods to grab all objects stored in the people collection — one for each iteration of the loop. These lines display each of the people collection's values.

Which is better? An enhanced for loop or an iterator? Java programmers prefer the enhanced for loop because the for loop involves less baggage — no iterator object to carry from one line of code to the next. But, the most programming-enhanced feature can be upgraded, streamlined, tweaked, and otherwise reconstituted. There's no end to the way you can improve upon your code.

About This Article

This article is from the book:

About the book author:

Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.

This article can be found in the category: