Java—Iterator接口介绍及使用

Iterator接口介绍

  Iterator称之为迭代器,是去遍历Collection、Map集合中的元素对象。

Iterator常用方法

  • boolean hasNext():判断是否还有下一个遍历元素,若还有未被遍历的元素,返回true;否则,返回false。
  • Object next():返回集合里的下一个元素;
  • void remove():删除集合里上一次next方法返回的元素;
  • void forEachRemaining(Consumer<? super E> action):Java 8 新增方法,可使用Lambda表达式遍历集合元素。内部通过hasNext()方法进行遍历,源码如下:
    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
    

Iterator使用示例

示例1:正确使用

public class DemoApplication {

    public static void main(String[] args) {

        Collection collection = new ArrayList();
        // 添加元素
        collection.add("add()方法");
        collection.add("1");
        collection.add("2.7");
        collection.add("value1");
        collection.add("value2");

        //遍历集合
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
            //next()方法
            String colStr = (String)iterator.next();
            System.out.println(colStr);
            //remove()方法
            if ("value2".equals(colStr)) {
                iterator.remove();
            }
        }

        System.out.println(collection);
        }
}

运行结果:

add()方法
1
2.7
value1
value2
[add()方法, 1, 2.7, value1]

  当使用Iterator遍历Collection集合时,集合内的元素不能被改变,只能通过Iterator的remove()方法删除上一次next()方法返回的集合元素才可以;否则会引起java.util.ConcurrentModificationException异常。

示例2:错误使用

在上述示例中我们将iterator.remove();换成collection.remove(colStr);

public class DemoApplication {

    public static void main(String[] args) {

        Collection collection = new ArrayList();
        // 添加元素
        collection.add("add()方法");
        collection.add("1");
        collection.add("2.7");
        collection.add("value1");
        collection.add("value2");

        //遍历集合
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
            //next()方法
            String colStr = (String)iterator.next();
            System.out.println(colStr);
            //remove()方法
            if ("value2".equals(colStr)) {
            	//改变了集合,抛出异常之处
                collection.remove(colStr);
            }
        }

        System.out.println(collection);
        }
}

运行结果:

add()方法
1
2.7
value1
value2
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.example.andya.demo.DemoApplication.main(DemoApplication.java:30)

Process finished with exit code 1

  上述异常示例中,我们可以看到在Iterator遍历Collection集合的过程中,通过删除集合元素修改了集合,程序运行时引发异常,而Iterator迭代器采用了快速失败机制(fail-fast),一旦在遍历过程中发现集合已被修改,程序立即会抛出ConcurrentModificationException异常,这可以避免多线程中共享资源问题。

示例3:Lambda表达式遍历

public class DemoApplication {

    public static void main(String[] args) {
        Collection collection = new ArrayList();
        // 添加元素
        collection.add("我");
        collection.add("爱");
        collection.add("中");
        collection.add("国");

        //遍历集合
        Iterator iterator = collection.iterator();
        //使用Lambda表达式遍历,目标类型是Consumer
        iterator.forEachRemaining(obj -> System.out.println(obj));
        }
}

运行结果

我
爱
中
国

示例4:foreach遍历

当然,除了使用Iterator接口去遍历,我们还可以通过foreach去遍历集合,系统依次将集合元素的值赋给迭代遍历。

**public class DemoApplication {

    public static void main(String[] args) {

        Collection collection = new ArrayList();
        // 添加元素
        collection.add("中");
        collection.add("国");
        collection.add("加");
        collection.add("油");

        //foreach遍历,系统依次将元素值赋给遍历object
        for (Object object : collection) {
            String str = (String) object;
            System.out.println(str);
        }
    }
}

运行结果

中
国
加
油
发布了101 篇原创文章 · 获赞 132 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Andya_net/article/details/105058700
今日推荐