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

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.

主站蜘蛛池模板: 尼玛县| 维西| 长泰县| 怀来县| 泸州市| 通江县| 休宁县| 任丘市| 邵东县| 寻乌县| 鲜城| 南江县| 维西| 苏尼特右旗| 太仆寺旗| 邛崃市| 板桥市| 咸丰县| 白沙| 高淳县| 邵阳市| 东兰县| 东丽区| 邛崃市| 泸定县| 军事| 延津县| 鄯善县| 合水县| 本溪| 石柱| 昌都县| 十堰市| 莒南县| 乐安县| 奉新县| 闽清县| 虹口区| 阿鲁科尔沁旗| 凌海市| 武宣县|