(13)迭代器模式
概念
迭代器主要用在集合的遍历。我们无需关心集合的底层是什么数据结构,直接使用集合中的迭代器即可达到遍历的效果。
不是有for循环吗?为什么还需要迭代器?
迭代器更像是面向对象的方式,用户只需关注拿到迭代器这个对象,就可以使用迭代器遍历这个对象的内部数据
实现方式
/**
* 迭代器
*/
public class Demo {
public static void main(String[] args) {
MyList myList = new MyList();
MyIterator it = myList.getMyIterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
// 迭代器接口
interface MyIterator {
boolean hasNext();
Object next();
}
// 自己的集合
class MyList {
static Object[] dataArr = new Object[]{"a", "b", "c", "d"};
public MyIterator getMyIterator() {
return new MyListIterator();
}
// 具体迭代器实现
class MyListIterator implements MyIterator {
int index = 0;
@Override
public boolean hasNext() {
if (index < dataArr.length) {
return true;
}
return false;
}
@Override
public Object next() {
if (this.hasNext()) {
return dataArr[index++];
}
return null;
}
}
}
a
b
c
d

浙公网安备 33010602011771号