“This is the 11th day of my participation in the August Gwen Challenge.

The concept and role of iterator patterns

(1) The concept of iterator pattern

The iterator pattern, also known as the cursor pattern, provides a way to access the elements of a collection/container object sequentially without exposing the internal representation of the collection. The iterator pattern provides consistent traversal behavior for different containers, regardless of the structure of the container’s content elements. It is a behavioral pattern.

The essence of the iterator pattern is to extract the collection object iteration behavior into the iterator, providing a consistent access interface.

(ii) The role of iterator pattern

Abstract iterators (ITrtators) : Abstract iterators define interfaces that access and iterate over elements

Concretriterators: Provide concrete element traversal behavior

3. Aggregate: Complex definitions of interfaces that provide concrete iterators

4. Concrete Aggregates: Create concrete iterators

The application scenario of iterator pattern

Access the contents of a collection object without exposing its internal representation

2. Provide a unified access interface for traversing different collection structures

Code examples of iterator patterns

Course:

public class Course {
    private String name;

    public Course(String name) {
        this.name = name;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name; }}Copy the code

The Iterator:

public interface Iterator<E> {

    E next(a);

    boolean hasNext(a);
}
Copy the code

CourseAggregate:

public interface CourseAggregate {

    void add(Course courses);

    void remove(Course courses);

    Iterator<Course> iterator(a);
}
Copy the code

IteratorImpl:

public class IteratorImpl<E> implements Iterator<E> {

    private List<E> list;
    private int cursor;
    private E element;

    public IteratorImpl(List list) {
        this.list = list;
    }

    @Override
    public E next(a) {
        System.out.println("Current location" + cursor + ":");
        element = list.get(cursor);
        cursor++;
        return element;
    }

    @Override
    public boolean hasNext(a) {
        returncursor == list.size(); }}Copy the code

CourseAggregateImpl:

public class CourseAggregateImpl implements CourseAggregate {

    private List courseList;

    public CourseAggregateImpl(List courseList) {
        this.courseList = courseList;
    }

    @Override
    public void add(Course course) {
        courseList.add(course);
    }

    @Override
    public void remove(Course course) {
        courseList.remove(course);
    }

    @Override
    public Iterator<Course> iterator(a) {
        return newIteratorImpl<>(courseList); }}Copy the code

The test class:

public class Main {

    public static void main(String[] args) {
        Course java = new Course("Java");
        Course python = new Course("Python");
        Course js = new Course("JavaScript");

        CourseAggregate courseAggregate = new CourseAggregateImpl(new ArrayList());

        courseAggregate.add(java);
        courseAggregate.add(python);
        courseAggregate.add(js);

        System.out.println("-- Course List --");
        printCourse(courseAggregate);
        courseAggregate.remove(js);
        System.out.println("-- Delete course list after operation --");
        printCourse(courseAggregate);
    }

    private static void printCourse(CourseAggregate courseAggregate) {
        Iterator<Course> iterator = courseAggregate.iterator();
        while(! iterator.hasNext()) { Course next = iterator.next(); System.out.println("" " + next.getName() + "" "); }}}Copy the code

Iterator pattern in the application of source code

In Iterator’s source code, hasNext() and next() methods are also defined.

public interface Iterator<E> {
    / /... Omit intermediate code comments
    boolean hasNext(a);
	/ /... Omit intermediate code comments
    E next(a);
    / /... Omit intermediate code comments
    default void remove(a) {
        throw new UnsupportedOperationException("remove");
    }
	/ /... Omit intermediate code comments
    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while(hasNext()) action.accept(next()); }}Copy the code

Within ArrayList is an internal class, Itr, that implements the Iterator interface and implements the hasNext() and next() methods

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess.Cloneable.java.io.Serializable {
    
    / /... Omit intermediate code
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        Itr() {
        }

        public boolean hasNext(a) {
            returncursor ! = size; }@SuppressWarnings("unchecked")
        public E next(a) {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
        / /... Omit intermediate code
    }
    / /... Omit intermediate code
}
Copy the code

Advantages and disadvantages of the iterator pattern

(1) Advantages

1. Polymorphic iteration: provide consistent traversal interfaces for different aggregation structures, that is, an iterative interface can access different associative objects

2. Simplify the collection object interface: The iterator pattern extracts the element iteration interface that the collection object itself should provide into the iterator, so that the combined object does not need to care about the specific iteration behavior

3, element iteration function diversification: each combination object can provide one or more different iterators, so that the same element aggregation structure can have different iteration behavior

4. Decoupled iteration and combination: the iterator mode encapsulates the specific iterative algorithm, and the change of the iterative algorithm will not affect the architecture of the collection object

(2) Disadvantages

1. For relatively simple traversal, the iterator method is cumbersome