Iterator主要有三个方法:hasNext()、next()、remove()详解

2023-05-16

一、Iterator的API

  关于Iterator主要有三个方法:hasNext()、next()、remove()

  hasNext:没有指针下移操作,只是判断是否存在下一个元素

  next:指针下移,返回该指针所指向的元素

 remove:删除当前指针所指向的元素,一般和next方法一起用,这时候的作用就是删除next方法返回的元素

二、迭代器原理

这里写图片描述

 1、当创建完成指向某个集合或者容器的Iterator对象是,这是的指针其实指向的是第一个元素的上方,即指向一个           空

 2、当调用hasNext方法的时候,只是判断下一个元素的有无,并不移动指针

 3、当调用next方法的时候,向下移动指针,并且返回指针指向的元素,如果指针指向的内存中没有元素,会报异             常。

 4、remove方法删除的元素是指针指向的元素。如果当前指针指向的内存中没有元素,那么会抛出异常。

三、迭代器的用途

   迭代器一般会用在遍历集合上面。

四、使用中注意的问题

Java中的Iterator是一种fail-fast的设计。

  当Iterator迭代一个容器的时候,如果此时有别的方法在更改Collection(容器)的内容,那么Iterator就会抛出

ConcurrentModificationException 。正如官方文档中反复强调的:

Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic 

 behavior at an undetermined time in the future.

为了避免此Exception的发生,可以采取的解决方法是:

1.如果当前单个线程在更改容器(add, delete….),那么迭代的时候采用iterator.remove()方法可以确保迭代器在查找next的时候,指针不会丢失。

while(iterator.hasNext() {

 Object item = iterator.next();

 iterator.remove();   //Important! 避免ConcurrentModificationException

 ......

}

2.如果当前有多个线程在对容器进行操作,例如一个线程正在向容器中写数据,而另一个线程在迭代此容器,这时候就必须考虑并发下的线程安全问题。ConcurrentModificationException官方文档第一句就指出:

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

这时候可以采用java.util.concurrent包下面的线程安全的容器解决此异常。

最后要说的是,ConcurrentModificationException应该永远被用于解决一个bug,而不是检查程序的正确性(try…catch…)。

    <script type="text/javascript">
        $(function () {
            $('pre.prettyprint code').each(function () {
                var lines = $(this).text().split('\n').length;
                var $numbering = $('<ul/>').addClass('pre-numbering').hide();
                $(this).addClass('has-numbering').parent().append($numbering);
                for (i = 1; i <= lines; i++) {
                    $numbering.append($('<li/>').text(i));
                };
                $numbering.fadeIn(1700);
            });
        });
    </script>

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Iterator主要有三个方法:hasNext()、next()、remove()详解 的相关文章

随机推荐