Java集合共有两种遍历方式
- 增强for循环(foreach)
- 迭代器
// Main方法:
public static void main(String[] args) {
// 创建集合
Collection collection = new ArrayList();
// 添加元素
collection.add("腊肉");
collection.add("香肠");
collection.add("卤肉");
System.out.println("集合中元素个数:" + collection.size());
System.out.println(collection.toString());
/**
* 遍历元素
* 第一种方式:增强for循环(foreach)
* 第二种方式:迭代器
*/
// 增强for循环(foreach)
for (Object o : collection) {
System.out.println(o);
}
System.out.println("-------------分割线-------------");
// 迭代器
Iterator iterator = collection.iterator();
while (iterator.hasNext()) { //判断是否有下一个元素
System.out.println(iterator.next());
// collection.remove(iterator.next()); -->并发修改异常
iterator.remove();
}
System.out.println("集合中元素个数:" + collection.size());
}
迭代器方法:
boolean hasNext(); // 如果仍有元素可以迭代,则返回true
E next(); // 放回迭代的下一个元素
default void remove(){} // 从迭代器指向的collection中移除迭代器返回的最后一个元素
迭代器简要原理图
迭代器删除操作不可以使用集合的删除方法,会报异常!
并发修改异常