package lesson2;
public class Demo6 {
public static void main(String[] args) {
MyArrayList list=new MyArrayList();
for(int i=0;i<10;++i)
{
list.add(new Cat(i));
}
MyIterator iter=list.iterator();
while(iter.hasNext())
{
System.out.println(iter.next());
}
}
}
interface MyIterator
{
Object next();
boolean hasNext();
}
class MyArrayList
{
private Object[] objs=new Object[10];
private int size=0;
public void add(Object e)
{
if(size==objs.length)
{
Object[] newObjs=new Object[objs.length*2];
System.arraycopy(objs,0,newObjs,0,objs.length);
objs=newObjs;
}
objs[size]=e;
++size;
}
public int size()
{
return size;
}
public Object get(int index)
{
Object obj=null;
try
{
obj=objs[index];
}catch(IndexOutOfBoundsException e)
{
e.printStackTrace();
}
return obj;
}
public MyIterator iterator()
{
return new MyIterator(){
private int index=0;
@Override
public Object next() {
Object obj=objs[index];
++index;
return obj;
}
@Override
public boolean hasNext() {
boolean bret=false;
if(index<objs.length)
{
bret=true;
}
return bret;
}};
}
}
class Cat
{
private int id;
public Cat(int id)
{
this.id=id;
}
public String toString()
{
return "Cat:"+id;
}
}
迭代器模式
最新推荐文章于 2024-03-07 19:08:34 发布