迭代器
-
概述 :
-
迭代器就是对Iterator的称呼 , 专门用来对Collection集合进行遍历使用的。学习迭代器的目的就是为了遍历集合
-
-
注意 :
-
只有继承/实现Iterable接口才具有迭代的能力
-
Collection接口继承了Iterable接口所以 , Collection及其子类都具备迭代的能力
-
-
获取迭代器对象的方式
-
通过Collection集合对象调用Iterable接口中的iterator方法 , 就可以获取迭代器对象
-
-
Iterator(迭代器)中的方法
boolean hasNext() 如果迭代具有更多元素,则返回 true 。 E next() 返回迭代中的下一个元素。 default void remove() 从底层集合中删除此迭代器返回的最后一个元素(可选操作)。 -
迭代器的注意事项
-
当迭代器迭代元素完成后,不能继续next获取元素,否则会报:NoSuchElementException
-
当迭代器在使用的过程中,不能使用集合对象直接增删元素。会导致报错ConcurrentModifica
-
举例
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class IteratorDemo1 {
public static void main(String[] args) {
//创建集合对象
Collection<String> collection = new ArrayList<String>();
//向集合中添加元素
collection.add("Java");
collection.add("MySQL");
collection.add("Mybatis");
collection.add("Spring");
//使用迭代器:遍历集合
//1、通过集合对象,获取到迭代器对象
Iterator<String> it = collection.iterator();
//2、while循环,判断迭代器对象中是否有下一个元素
while (it.hasNext()) {
//3、使用迭代器对象,取出下一个元素
String str = it.next();//泛型好处:不需要进行强制类型转换
System.out.println(str);
}
}
}