每一种容器它都有自己的一种遍历方式,比方说ArrayList有for循环遍历,LinkedList也有自己的链表遍历方式,二叉树有前中后序遍历方式等等,但是它们的遍历方式都不统一,iterator接口便统一了遍历方式,以下是代码片段,以ArrayList为例.
/**
* @Title: MyIterator
* @Description:自己写的迭代器
* @Auther:
* @Version: 1.0
* @create 2019/3/31 12:57
*/
public interface MyIterator {
boolean hasNext();
Object next();
}
/**
* @Title: Collection
* @Description:
* @Auther:
* @Version: 1.0
* @create 2019/3/31 12:49
*/
public interface Collection {
void add(Object object);
int size();
}
/**
* @Title: MyArrayList
* @Description: 用内部类的方式实现
* @Auther:
* @Version: 1.0
* @create 2019/3/31 12:50
*/
public class MyArrayList implements Collection {
private Object[] objects = new Object[10];
private int index = 0;
@Override
public void add(Object object) {
if(index==objects.length){
Object[] newObjects = new Object[objects.length*2];
System.arraycopy(objects,0,newObjects,0,objects.length);
objects = newObjects;
}
objects[index]=object;
index++;
}
@Override
public int size() {
return index;
}
public MyIterator iterator(){
return new ArrListIterator();
}
private class ArrListIterator implements MyIterator{
private int currentIndex=0;
public ArrListIterator() {
super();
}
@Override
public boolean hasNext() {
if(currentIndex>=index) return false;
else return true;
}
@Override
public Object next() {
Object o = objects[currentIndex];
currentIndex++;
return o;
}
}
}
/**
* @Title: Test
* @Description: 测试
* @Auther:
* @Version: 1.0
* @create 2019/3/31 13:05
*/
public class Test {
public static void main(String[] args) {
MyArrayList list = new MyArrayList();
for (int i = 0; i < 15; i++) {
list.add(i);
}
MyIterator iterator = list.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}