As we all know, Java is a high-level language in the programming language. In the world of java, there have been predecessors who have encapsulated various useful frameworks, tool classes and so on for us. The iterator mode that I want to talk about today has also been encapsulated.
Is the for loop iterator that we often use.Or Iterator, these are already packaged.We often use it, and some readers may not know it's an iterator pattern.The author has not yet done so in practice
Define your own iterator to implement your own business traversal.First look at the class diagram
Dahua Design Mode-Class Diagram
After looking at the class diagram, we can clearly see that what we demo need to do is first define a set of our own that will create an iterator.Collection interfaces require four methods to see the class diagram.
Look at the author's demo
/** * Iterator Interface */ public interface Iterator<T> { public T first(); public T next(); public Boolean hasNext(); public T current(); }
/** * Collection Interface */ public interface ICollection<T> { public Iterator<T> createIterator(); }
/** * Collection Implementation Class */ public class MyCollection<T> implements ICollection<T>{ List<T> list = new ArrayList<T>(); @Override public Iterator<T> createIterator() { return new MyIterator<>(list); } public void add(T t) { list.add(t); } public void remove(T t) { list.remove(t); } }
/** * Iterator Implementation Class */ public class MyIterator<T> implements Iterator<T> { private int cursor; private List<T> list; public MyIterator(List<T> list){ this.list = list; } @Override public T first() { cursor = 0; return list.get(0); } @Override public T next() { T t = null; if (hasNext()) { t = list.get(cursor); } cursor ++; return t; } @Override public Boolean hasNext() { return cursor < list.size(); } @Override public T current() { return list.get(cursor); } }
/** * Client */ public class Test { public static void main(String[] args) { MyCollection<String> myCollection = new MyCollection<>(); myCollection.add("a"); myCollection.add("b"); myCollection.add("c"); myCollection.add("d"); myCollection.add("e"); Iterator<String> iterator = myCollection.createIterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } }
The results are as follows:
a
b
c
d
e
This is a simple demo, and I think the iterator java is already encapsulated for us.We understand how it works, and it is important to absorb its design ideas.I want to help my learning buddies understand the iterator pattern.