迭代器接口与集合接口还有实现实现类的关系
为什么要用迭代的方式呢?
因为我们知道Collection接口的其中一个子接口Set是没有索引的,因此不能通过索引的方式来遍历结合,故而引入了迭代器。
迭代器遍历的原理
注意事项:
- 在进行集合元素获取时,如果集合中已经没有元素了,还继续使用迭代器的next方法,将会抛出java.util.NoSuchElementException没有集合元素异常。
- 在进行集合元素获取时,如果添加或移除集合中的元素 , 将无法继续迭代 , 将会抛出ConcurrentModificationException并发修改异常.
使用
Collection集合存储整数并遍历
步骤:
- 创建Collection集合对象,并添加数据,数据类型Integer
- 集合对象调用iterator方法,获取迭代器Iterator接口的实现对象
- 循环遍历
- 迭代器对象调用hasNext方法,判断是否有下一个元素
- 如果有,迭代器对象调用next方法,获取下一个元素
public static void main(String[] args) {
//1.创建Collection集合对象,并添加数据,数据类型Integer
Collection<Integer> coll = new ArrayList<>();
for (int i = 0; i < 10; i++) {
coll.add(new Random().nextInt(100));
}
//2.集合对象调用iterator方法,获取迭代器Iterator接口的实现对象
Iterator<Integer> it = coll.iterator();
while(it.hasNext()){
Integer next = it.next();
System.out.println(next);
}
}
增强for循环
迭代器的遍历写法十分繁琐,所以JDK4.5以后版本引入了增强for循环,增强for循环在变异以后还是迭代器的写法。
*.java文件
public static void main(String[] args) {
Collection<String> coll = new ArrayList<>();
coll.add("C++");
coll.add("Java");
coll.add("php");
coll.add("python");
// 增强for循环
for (String s : coll) {
System.out.println(s);
}
}
*.class文件
public static void main(String[] args) {
Collection<String> coll = new ArrayList();
coll.add("C++");
coll.add("Java");
coll.add("php");
coll.add("python");
Iterator var3 = coll.iterator();
while(var3.hasNext()) {
String s = (String)var3.next();
System.out.println(s);
}
}
注意事项:
- 增强for循环必须有被遍历的目标,目标只能是Collection或者是数组;
- 增强for(迭代器)仅仅作为遍历操作出现,不能对集合进行增删元素操作,否则抛出ConcurrentModificationException并发修改异常