再上一篇的基础上我们来模拟下容器的遍历。我们先来模拟ArrayList的遍历,首先同样先在Collection接口中定义遍历方法并且新加入一个遍历的接口Iterator接口。如下:
package com.iteritor;
public interface Iterator {
//获得下一个对象
public Object next();
//判断是否有下一个
public boolean hasNext();
}
collection接口
package com.iteritor;
public interface Collection {
//向容器添加元素
public void add(Object o);
//容器的长度
public int size();
//容器的遍历
public Iterator iterator();
}
接着我们在ArrayList中实现遍历,在这儿我们在ArrayList中新加入一个内部类ArrayListIterator。让他去实现遍历接口。而在ArrayList中我们只需要返回一个ArrayListIterator即可。
package com.iteritor;
public class ArrayList implements Collection{
private int index = 0;
private Object[] objects = new Object[10];
/**
* 数组长度自动扩充
* @param o
*/
public void add(Object o){
if (index==objects.length) {
Object[] newObjects = new Object[objects.length*2];
System.arraycopy(objects, 0, newObjects, 0, objects.length);
objects = newObjects;
}
objects[index]=o;
index++;
}
/**
* 查看长度
* @return
*/
public int size(){
return index;
}
/**
* 数组的遍历
*/
public Iterator iterator(){
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator{
private int currentIndex = 0;
@Override
public Object next() {
Object o = objects[currentIndex];
currentIndex++;
return o;
}
@Override
public boolean hasNext() {
if (currentIndex >= index) {
return false;
}
return true;
}
}
}
为方便测试同样新加了一个Cat类
package com.model;
public class Cat {
private int id;
public Cat(int id) {
this.id = id;
}
public String toString(){
return "cat"+id;
}
}
下面是测试类
package com.test;
import com.iteritor.ArrayList;
import com.iteritor.Collection;
import com.iteritor.Iterator;
import com.model.Cat;
public class Test2 {
public static void main(String[] args) {
Collection arrayList = new ArrayList();
for (int i = 0; i < 15; i++) {
arrayList.add(new Cat(i));
}
System.out.println(arrayList.size());
Iterator it = arrayList.iterator();
while (it.hasNext()) {
System.out.println(it.next()+"");
}
}
}
九层之台,始于累土
用心 点滴 积累