Java Reference
In-Depth Information
5. private ArrayList items = new ArrayList();
6.
7. public void add(String item){
8. if (!items.contains(item)){
9. items.add(item);
10. }
11. }
12. public void add(String item, int position){
13. if (!items.contains(item)){
14. items.add(position, item);
15. }
16. }
17. public void remove(String item){
18. if (items.contains(item)){
19. items.remove(items.indexOf(item));
20. }
21. }
22.
23. public int getNumberOfItems(){ return items.size(); }
24. public Iterator getIterator(){ return items.iterator(); }
25. public String getListName(){ return listName; }
26. public void setListName(String newListName){ listName = newListName; }
27.
28. public String toString(){ return listName; }
29. }
Both classes can provide an Iterator, so it's straightforward to write code to move through their elements.
ListPrinter shows how the Iterators could be used to print the contents of collections out in their String form.
The class has three methods: printToDoList , printToDoListCollection and printIteratingElement . In all
three methods, the iteration process is based around a very simple while loop.
Example A.70 ListPrinter.java
1. import java.util.Iterator;
2. import java.io.PrintStream;
3. public class ListPrinter{
4. public static void printToDoList(ToDoList list, PrintStream output){
5. Iterator elements = list.getIterator();
6. output.println(" List - " + list + ":");
7. while (elements.hasNext()){
8. output.println("\t" + elements.next());
9. }
10. }
11.
12. public static void printToDoListCollection(ToDoListCollection lotsOfLists,
PrintStream output){
13. Iterator elements = lotsOfLists.getIterator();
14. output.println("\"To Do\" List Collection:");
15. while (elements.hasNext()){
16. printToDoList((ToDoList)elements.next(), output);
17. }
18. }
19.
20. public static void printIteratingElement(Iterating element, PrintStream output){
21. output.println("Printing the element " + element);
22. Iterator elements = element.getIterator();
23. while (elements.hasNext()){
24. Object currentElement = elements.next();
25. if (currentElement instanceof Iterating){
26. printIteratingElement((Iterating)currentElement, output);
27. output.println();
28. }
29. else{
30. output.println(currentElement);
31. }
32. }
33. }
34. }
The method printIteratingElement best demonstrates the power of combining the Iterator pattern with
polymorphism. Here, any class that implements Iterating can be printed in String form. The method makes no
assumptions about the underlying collection structure except that it can produce an Iterator .
This example uses two support classes, DataCreator and DataRetriever , to produce a sample set of to-do lists
and store them in a file.
Search WWH ::




Custom Search