Iterator
使用 Iterator 接口遍历集合Collection元素
- Iterator对象称为迭代器(设计模式的一种),主要用于遍历 Collection 集合中的元素
- 所有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了Iterator接口的对象
- Iterator 仅用于遍历集合,Iterator 本身并不提供承装对象的能力。如果需要创建 Iterator 对象,则必须有一个被迭代的集合
itertor接口的方法
hasNext:没有指针下移操作,只是判断是否存在下一个元素
next:指针下移,返回该指针所指向的元素
remove:删除当前指针所指向的元素,一般和next方法一起用,这时候的作用就是删除next方法返回的元素
注意:在调用it.next()方法之前必须要调用it.hasNext()进行检测。若不调用,且下一条记录无效,直接调用it.next()会抛出NoSuchElementException异常。
Iterator和ListIterator主要区别
一、ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历。但是ListIterator有hasPrevious()和previous()方法,可以实现逆向(顺序向前)遍历。Iterator就不可以。
二、ListIterator可以定位当前的索引位置,nextIndex()和previousIndex()可以实现。Iterator 没有此功能。
三、ListIterator有add()方法,可以向List中插入对象,而Iterator不能。
四、都可实现删除对象,但是ListIterator可以实现对象的修改,set()方法可以实现。Iterator仅能遍历,不能修改。因为ListIterator的这些功能,可以实现对LinkedList等List数据结构的操作。
五、ListIterator 接口继承了 Iterator 接口,提供了专门操作 List 的方法:
void add()
boolean hasPrevious()
Object previous()
Boolean hasNext()
Object next()
for 、foreach与iterator
1、for循环一般用来处理比较简单的有序的,可预知大小的集合或数组
2、foreach可用于遍历任何集合或数组,而且操作简单易懂,他唯一的不好就是需要了解集合内部类型
3、iterator是最强大的,他可以随时修改或者删除集合内部的元素,并且是在不需要知道元素和集合的类型的情况下进行的,当你需要对不同的容器实现同样的遍历方式时,迭代器是最好的选择!
借鉴:https://blog.csdn.net/iamkila/article/details/7266890
实现代码
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.junit.Test;
public class TestIterator {
@Test
public void test4() {//foreach遍历普通对象
String[] strings=new String[] {
"cc","xx","aa"
};
for(String s:strings) {
System.out.println(s);
}
}
@Test
public void test3() {
Collection collection=new ArrayList();
System.out.println(collection.size());//返回集合的个数
collection.add(123);//添加一个元素
collection.add("sasd");
collection.add(new Date(0));
collection.add("ss");
collection.add(new Person(1,"samuro"));
for(Object i:collection) {
System.out.println(i);
}
Iterator iterator=collection.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
@Test
public void test2() {
Collection collection=new ArrayList();
System.out.println(collection.size());//返回集合的个数
collection.add(123);//添加一个元素
collection.add("sasd");
collection.add(new Date(0));
collection.add("ss");
collection.add(new Person(1,"samuro"));
Iterator iterator=collection.iterator();
//错误写法,应该直接使用iterator.next()
while((iterator.next())!=null) {
System.out.println(iterator.next());
}
}
@Test
public void test1() {
Collection collection=new ArrayList();
System.out.println(collection.size());//返回集合的个数
collection.add(123);//添加一个元素
collection.add("sasd");
collection.add(new Date(0));
collection.add("ss");
collection.add(new Person(1,"samuro"));
Iterator iterator=collection.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}