Java 设计模式 之 迭代器模式
Posted verejava
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 设计模式 之 迭代器模式相关的知识,希望对你有一定的参考价值。
http://www.verejava.com/?id=16999127808571
package com.iterator.theory;
import java.util.Arrays;
public class TestIterator
{
public static void main(String[] args)
{
List list=new ArrayList();
list.add("李阳");
list.add("王涛");
list.add("张飒");
Iterator iter=list.iterator();
while(iter.hasNext())
{
Object obj=iter.next();
System.out.println(obj);
}
}
}
package com.iterator.theory;
public interface Iterator
{
public boolean hasNext();
public Object next();
}
package com.iterator.theory;
public class IteratorImpl implements Iterator
{
private int index;
private List list;
public IteratorImpl(List list)
{
this.list=list;
}
@Override
public boolean hasNext()
{
return index<list.size();
}
@Override
public Object next()
{
Object element=null;
if(index<list.size())
{
element=list.get(index);
index++;
}
return element ;
}
}
package com.iterator.theory;
public interface List
{
public void add(Object element);
public Object get(int index);
public int size();
public Iterator iterator();
}
package com.iterator.theory;
import java.util.Arrays;
public class ArrayList implements List
{
private int initCapacit=20;
private int size;
private Object[] elementData;
public ArrayList()
{
elementData=new Object[initCapacit];
}
@Override
public void add(Object element)
{
if(size<initCapacit)
{
elementData[size]=element;
size++;
}
else
{
elementData=Arrays.copyOf(elementData, size);
elementData[size]=element;
size++;
}
}
@Override
public Object get(int index)
{
return elementData[index];
}
@Override
public int size()
{
return size;
}
@Override
public Iterator iterator()
{
return new IteratorImpl(this);
}
}
http://www.verejava.com/?id=16999127808571
以上是关于Java 设计模式 之 迭代器模式的主要内容,如果未能解决你的问题,请参考以下文章