February 28, 2021
Hot Topics:

Working With Design Patterns: Iterator

  • By Jeff Langr
  • Send Email »
  • More Articles »

Listing 2: SequenceTest

import static org.junit.Assert.*;
import org.junit.*;
import java.util.*;

public class SequenceTest {
   private List<Integer> ints;

   public void createCollection() {
      ints = new ArrayList<Integer>();

   public void singleEntry() {
      verifySequence(new Sequence(0, 0), 0);

   public void twoEntries() {
      verifySequence(new Sequence(1, 2), 1, 2);

   public void multipleEntries() {
      verifySequence(new Sequence(5, 10), 5, 6, 7, 8, 9, 10);

   public void negativeNumbers() {
      verifySequence(new Sequence(-2, 2), -2, -1, 0, 1, 2);

   public void increment() {
      verifySequence(new Sequence(0, 5, 2), 0, 2, 4);

   public void incrementIncludesLimit() {
      verifySequence(new Sequence(0, 6, 2), 0, 2, 4, 6);

   private void verifySequence(Sequence sequence,
      int... expectedValues) {
      for (int i: sequence)
      assertEquals(expectedValues.length, ints.size());
      for (int i: expectedValues)

What's the value? It affords more concise code, and there are benefits of Sequence being an object. You can pass around a sequence (and persist it), as opposed to having to pass around discrete numbers representing the range and other information, such as the step value. You also could extend its capabilities without altering code that uses a sequence. For example, you could provide the ability to suspend a sequence, and later have it resume where it left off.

Iteration is one of the more prevalent operations in computing. It's fitting that you find as concise, consistent, and expressive a manner to accomplish it. Sun has produced three Java collection iteration mechanisms to date, improving the solution each time. No doubt, you'll see another mechanism in the not-too-distant future.

About the Author

Jeff Langr is a veteran software developer with over a quarter century of professional software development experience. He's written two books, including Agile Java: Crafting Code With Test-Driven Development (Prentice Hall) in 2005. Jeff has contributed a couple chapters to Uncle Bob Martin's upcoming book, Clean Code. Jeff has written over 75 articles on software development, with over thirty appearing at Developer.com. You can find out more about Jeff at his site, http://langrsoft.com, or you can contact him via email at jeff at langrsoft dot com.

Page 3 of 3

This article was originally published on July 9, 2008

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date