1.设计Iterator接口
package com.hello.iterator;
public interface Iterator {
Object next();//下一个元素
boolean hasNext();//是否有下一个元素
}
2.设计Collection接口
package com.hello.iterator;
public interface Collection{
void add(Object o);//添加一个元素
int size();//返回元素的总数
Iterator iterator();//返回此集合类专用的迭代器
}
package com.hello.iterator;
/**
* 模仿ArrayList
*/
public class ArrayList implements Collection{
private Object[] obj = new Object[10];//元素容器,默认为10个
private int index;//记录下一个元素要插入的位置
public void add(Object o) {
if (index >= obj.length) {//超过容器的容量,扩容
Object[] newObj = new Object[obj.length * 2];
System.arraycopy(obj, 0, newObj, 0, obj.length);
obj = newObj;
}
obj[index++] = o;
}
public int size() {
return index;
}
public Iterator iterator() {
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator{
private int currentIndex = 0;//记录当前的元素下标
public Object next() {
return obj[currentIndex++];
}
public boolean hasNext() {
if(currentIndex<index)
return true;
else
return false;
}
}
}
4.编写测试类测试
package com.hello.iterator;
public class Test {
public static void main(String[] args) {
Collection c = new ArrayList();
for (int i = 0; i < 22; i++) {
c.add("haha"+":"+i);
}
System.out.println(c.size());
Iterator it = c.iterator();
while(it.hasNext()) {
Object o = it.next();
System.out.print(o + " ");
}
}
}
完整demo代码:
http://download.csdn.net/detail/shaoyangdd/8396051