官术网_书友最值得收藏!

Programming the design pattern

The first part of our source code includes import statements for ArrayList and Iterator. In the main() method, we create a colonies ArrayList of strings. We then populate 12 elements to the ArrayList:

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {

public static void main(String[] args) {

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

colonies.add("Aerlion");
colonies.add("Aquaria");
colonies.add("Canceron");
colonies.add("Caprica");
colonies.add("Gemenon");
colonies.add("Leonis");
colonies.add("Libran");
colonies.add("Picon");
colonies.add("Sagittaron");
colonies.add("Scorpia");
colonies.add("Tauron");
colonies.add("Virgon");

The second half of the source code does three things. First, it instantiates an iterator named myIterator. Next, a simple text header is printed to the console. Lastly, the code iterates through the ArrayList, printing each element:

        // instantiate iterator
Iterator myIterator = colonies.iterator();

// console output
System.out.println("\n\nOriginal Colonies of Kobol:");

// iterate through the list
while (myIterator.hasNext())
System.out.println("\t\t" + myIterator.next());

}
}

The iteration was able to take place without knowing that the colonies object stored its data in an ArrayList.

The output of our sample application is illustrated here:

Iterator application output

This section featured the source code and output, demonstrating the iterator design pattern.

主站蜘蛛池模板: 洛宁县| 信丰县| 沙湾县| 嘉峪关市| 南乐县| 屏山县| 游戏| 扬中市| 年辖:市辖区| 苍溪县| 阜平县| 射阳县| 黄冈市| 民乐县| 汤原县| 南丰县| 夏津县| 栖霞市| 分宜县| 江都市| 焉耆| 上饶县| 德格县| 凉山| 岗巴县| 桃源县| 江北区| 厦门市| 花莲县| 隆回县| 友谊县| 卢龙县| 金昌市| 达州市| 右玉县| 丰顺县| 凤冈县| 鄂托克前旗| 安乡县| 疏附县| 双鸭山市|