迭代器 Iterator 使用

Iterator 接口提供遍历任何 Collection 的接口。我们可以从一个 Collection 中使用迭代器方法来获取迭代器实例。迭代器取代了 java 集合框架中的 Enumeration,迭代器允许调用者在迭代过程中移除元素。

List list = new ArrayList<>();
Iterator it = list.iterator();
while(it.hasNext()){
String obj = it.next();
System.out.println(obj);
}

Iterator 的特点是更加安全,因为它可以确保,在当前遍历的集合元素被更改的时候,就会抛出 ConcurrentModificationException 异常。

posted @ 2022-10-20 16:05  ~春树暮云  阅读(21)  评论(0)    收藏  举报