Java—Iterator接口介绍及使用

Iterator接口介绍

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

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异常。ui

示例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);
        }
}

运行结果:code

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);
        }
    }
}

运行结果rem

中
国
加
油
相关文章
相关标签/搜索