Definition: Used to access the elements of the collection object sequentially, and do not need to know the underlying representation of the collection object.
Features:
1. It supports traversing an aggregate object in different ways.
2. Iterator simplifies the aggregation class.
3. There can be multiple traversals on the same aggregation.
4. In the iterator mode, it is very convenient to add new aggregation classes and iterator classes, without modifying the original code.
Applications in enterprise-level development and common frameworks: Java collections implement iterators
Specific examples:
public class Demo { public static void main(String[] args) { ActualContainer container = new ActualContainer(); for(int i = 5 ; i < 20 ; i++){ container.add(i); } Iterator iterator = container.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } }}/** * Iterator interface, containing commonly used iterator methods*/interface Iterator{ public boolean hasNext(); public Object next();}/** * Container interface: contains a method to obtain iterator*/interface Container{ public Iterator iterator();}/** * Specific implementation class* @author jiaoyuyu * */class ActualContainer implements Container{ private List<Object> list = new ArrayList<>(); public void add(Object obj){ this.list.add(obj); } public void remove(Object obj){ this.list.remove(obj); } public Object get(int index){ if(index <= (this.list.size() - 1)){ return this.list.get(index); } return null; } public Iterator iterator() { return new ActualIterator(); } private class ActualIterator implements Iterator{ private int pointer = 0; public boolean hasNext() { return this.pointer < list.size() ? true : false; } public Object next() { if(this.pointer < list.size()){ Object obj = list.get(pointer); pointer++; return obj; } return null; } }}The iterator pattern is a relatively simple pattern, mainly used to traverse objects of a collection type.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.