Iterator (iterator) traverse the collection element Collection

Iterator (iterators) is an interface, its role is to traverse all the elements of container members, as well as Java Collections Framework, but it Map Series Collection and collection is not the same, and Map Collection series is mainly used to contain a collection of other objects, the iterator is mainly used to traverse (i.e., iterates) collection collection element.

Iterator interface hides the underlying details of the implementation class Collection, Collection offers a collection of elements traversing a unified programming interface to the application. Iterator interface defined in the following four methods.

	boolean hasNext():如果被迭代的集合元素还没有被遍历完,则返回 true。
	
	Object next():返回集合里的下一个元素。
	
	void remove():删除集合里上一次 next 方法返回的元素。
	
	void forEachRemaining(Consumer action):这是 Java 8 为 Iterator 新增的默认方法,该方法可使用 Lambda 表达式来遍历集合元素。

Iterator to traverse through the set of elements of the interface.

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

public class IteratorTest {
    public static void main(String[] args) {
        // 创建一个集合
        Collection objs = new HashSet();
        objs.add("Java教程");
        objs.add("C语言教程");
        objs.add("python教程");
        // 调用forEach()方法遍历集合
        // 获取books集合对应的迭代器
        Iterator it = objs.iterator();
        while (it.hasNext()) {
            // it.next()方法返回的数据类型是Object类型,因此需要强制类型转换
            String obj = (String) it.next();
            System.out.println(obj);
            if (obj.equals("百度C语言")) {
                // 从集合中删除上一次next()方法返回的元素
                it.remove();
            }
            // 对book变量赋值,不会改变集合元素本身
            obj = "百度Python语言";
        }
        System.out.println(objs);
    }
}

It can be seen from the above code, only through the collection Iterator created if needed Iterator objects, there must be a collection of iterations. Iterator no collection value does not exist.

note: Iterator must be attached to the Collection object, if an Iterator object, there must be a Collection object associated with it. Iterator provides two methods to iterate Collection the collection of elements, and can be deleted by the collection remove () method on a next () method returns a collection of elements.

When you access a collection element uses an Iterator Collection, Collection of elements of the collection can not be changed, the only way to remove a next () method returns a collection of elements through the remove Iterator () can, otherwise it will lead to "java.util. ConcurrentModificationException "exception. The following program demonstrates this.

public class IteratorErrorTest {
    public static void main(String[] args) {
        // 创建一个集合
        Collection objs = new HashSet();
        objs.add("百度Java教程");
        objs.add("百度C语言教程");
        objs.add("百度C++教程");
        // 获取books集合对应的迭代器
        Iterator it = objs.iterator();
        while (it.hasNext()) {
            String obj = (String) it.next();
            System.out.println(obj);
            if (obj.equals("百度C++教程")) {
                // 使用Iterator迭代过程中,不可修改集合元素,下面代码引发异常
                objs.remove(obj);
            }
        }
    }
}

The output is:

百度C++教程
Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextNode(Unknown Source)
        at java.util.HashMap$KeyIterator.next(Unknown Source)
        at IteratorErrorTest.main(IteratorErrorTest.java:15)

Line 15 is located within an Iterator block of code, which is set in an Iterator Collection Collection modified during the collection, so the program will throw an exception at runtime.

An Iterator uses the fast failure (fail-fast) mechanism, upon detection of the set in the iterative process has been modified (usually other threads to modify the program), the program immediately raises ConcurrentModificationException exception, instead of displaying the modified As a result, to avoid potential problems caused by shared resources.

	快速失败(fail-fast)机制,是 Java Collection 集合中的一种错误检测机制。

note: If the above procedure was changed to delete the "Baidu C language tutorial" string, no exception is raised. For HashSet and ArrayList back, etc., remove elements can lead to abnormal iteration. Only when you delete a specific element in the collection will not throw an exception, which is determined by a set of code that implements the class.

Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104715828