Java For Dummies, 8th Edition
Book image
Explore Book Buy On Amazon
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(diskScanner.nextLine());

}

people.remove(0);

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

Iterator iterator = people.iterator();

while (iterator.hasNext()) {

out.println(iterator.next());

}

diskScanner.close();

}

}

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:

Barry Burd, PhD, is a veteran author and educator. At the University of Illinois, he was named five times to the university-wide List of Teachers Ranked as Excellent by their Students. He has written several books on Java and Android development.

This article can be found in the category: