Hello, I’m Chenxi. I’m glad you can read it. This article introduces you to the iterator pattern of Java design patterns, briefly explains how to use Iterator, and shares it with beginners. Let’s make progress together!
Article Directory
One, iterator introduction
Introduction to iterator mode
The so-called iterator pattern is to provide a way to sequentially access each element in an aggregate object, rather than exposing its internal representation. The iterator pattern is to delegate the responsibility of iterating elements to the iterator instead of the aggregate object. We can iterate the aggregate object even without knowing the internal structure of the aggregate object.
Through the iterator pattern, the structure of the aggregated object is made simpler. It does not need to focus on the traversal of its elements, but only needs to focus on what it should focus on, which is more in line with the single responsibility principle.
Let's take a closer look and briefly take a look at its methods!
public interface Iterator<E> {
boolean hasNext();//判断是否存在下一个对象元素
E next();//获取下一个元素
void remove();//移除元素
}
Iterator pattern: A method of traversing and accessing each element in the aggregate object without exposing the internal structure of the object.
Two, ArrayList case
First, we create a collection, and then use iterators successively; for loops; foreach to see the effect of printing;
public class IteratorTest {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("你好我是辰兮");
arrayList.add("很高兴你能来阅读");
arrayList.add(2020);
arrayList.add("一起进步");
Iterator iterable = arrayList.iterator();
//配合while()循环实现遍历输出
while (iterable.hasNext()){
System.out.println("while循环出来的数据是:"+iterable.next());
}
//while()中的判断条件it.hasNext()用于判断it中是否还有下一元素,有的话就继续循环,输出语句中的it.next()既可以使“指针”往后走一位,又能将当前的元素返回,用于输出。
System.out.println("======================================");
//配合for()循环实现遍历输出:
for(Iterator it = arrayList.iterator(); it.hasNext();){
System.out.println("for循环出来的数据是:"+it.next());
//可以自己调用移除方法测试
//it.remove();
}
System.out.println("======================================");
//foreach 循环来代替Iterator
for (Object a:arrayList) {
System.out.println("foreach出来的数据是:"+a);
}
//for each 不适合用来增删元素,如果单纯用来遍历元素,这种写法也许会更简洁一点。
}
}
operation result
while循环出来的数据是:你好我是辰兮
while循环出来的数据是:很高兴你能来阅读
while循环出来的数据是:2020
while循环出来的数据是:一起进步
======================================
for循环出来的数据是:你好我是辰兮
for循环出来的数据是:很高兴你能来阅读
for循环出来的数据是:2020
for循环出来的数据是:一起进步
======================================
foreach出来的数据是:你好我是辰兮
foreach出来的数据是:很高兴你能来阅读
foreach出来的数据是:2020
foreach出来的数据是:一起进步
Process finished with exit code 0
Remark here. If you use removeIDEA in foreach, it will also have its own prompt. Foreach is not suitable for adding and deleting elements.
Source code of the iterator method: When the iterator object calls iterator(), it returns the Iterator itself
/**
* Returns an iterator over the elements in this list in proper sequence.
*
* <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @return an iterator over the elements in this list in proper sequence
*/
public Iterator<E> iterator() {
return new Itr();
}
When learning iterator for the first time, I always feel that this word and this grammar are not easy to remember and very awkward. If you don’t understand well, just look at the source code to know why.
Three, HashMap case
We create a HashMap object, and then use the iterator; for loop; foreach to see the effect of printing;
public class IteratorMapTest {
public static void main(String[] args) {
HashMap<String,String> map = new HashMap<>();
map.put("1","hello");
map.put("2","辰兮");
map.put("3","一起进步");
map.put("4","fighting");
Iterator<Map.Entry<String, String>> iterable = map.entrySet().iterator();
//while循环测试
while (iterable.hasNext()){
System.out.println("while循环中测试:"+iterable.next());
}
System.out.println("=============================");
//for循环测试
for ( Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();it.hasNext();){
System.out.println("for循环测试"+it.next());
}
System.out.println("=============================");
//Map接口下的iterator应用方法与Collection中的略微有些不同,用到了entrySet()方法,entrySet()用来返回整个键—值对。
//foreach测试数据
for (Object object:map.entrySet()) {
System.out.println("foreach测试数据:"+object);
}
}
}
operation result
while循环中测试:1=hello
while循环中测试:2=辰兮
while循环中测试:3=一起进步
while循环中测试:4=fighting
=============================
for循环测试1=hello
for循环测试2=辰兮
for循环测试3=一起进步
for循环测试4=fighting
=============================
foreach测试数据:1=hello
foreach测试数据:2=辰兮
foreach测试数据:3=一起进步
foreach测试数据:4=fighting
Process finished with exit code 0
Four, expansion related
Cannot delete elements in the collection when iterator traverses
When using Iterator, it is forbidden to change the size and structure of the traversed container. For example: When using Iterator to iterate, if add and remove operations are performed on the collection, ConcurrentModificationException will occur .
Case
public class Test {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
list.remove(iterator.next());
}
}
}
operation result
1
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at com.example.rabbitmq.test.Test.main(Test.java:21)
Process finished with exit code 1
The best investment is to invest in yourself.
2020.09.26 May you all go to be in your love!