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

posted @ 2018-06-28 09:22  verejava  阅读(106)  评论(0编辑  收藏  举报