list遍历和删除
Iterator
List<String> list = new ArrayList<>();
Iterator<String> it = list. iterator();
while(it. hasNext()){
String obj = it. next();
System. out. println(obj);
}
只能单向遍历,但更加安全,可以确保当前遍历的集合元素被更改后,会抛出ConcurrentModificationException 异常。
遍历list的方式
- for循环遍历:在集合外部维护一个计数器,依次读取到最后一个元素时停止
- 迭代器遍历:iterator
- foreach遍历:内部也是采用的iterator的方式,使用时不需要显式声明iterator,操作简单,但在遍历过程中只能做简单的遍历,无法对数据进行操作
Collections 框架中提供了一个 RandomAccess 接口,可以用来标记list的子类是否支持 Random Access。
如果没有实现该接口,说明不支持Random Access,如linkedlist;
实现该接口的类,可以迅速遍历集合,平均时间复杂度为O(1);
Iterator 和 ListIterator的区别
- Iterator 只能单向遍历,而 ListIterator 可以双向遍历(向前/后遍历)。
- Iterator 可以遍历 Set 和 List 集合,而 ListIterator 只能遍历 List。
删除
Iterator<Integer> it = list.iterator();
while(it.hasNext()){
it.remove();
}