【设计模式】Iterator设计作业-设计LinkedList的iterator

完成了上次迭代器设计的作业: http://blog.csdn.net/acmman/article/details/43920153
LinkedList也需要写一个iterator方法,返回一个实现了Iterator的对象。该如何写?

LinkedList.java:
package cn.edu.hpu.iterator;

public class LinkedList implements Collection{
	Node head=null;//头节点(以后的元素通过next得到)
	Node tail=null;//尾节点
	int size=0;
	public void add(Object o){
		Node n=new Node(o,null);
		if(head==null){
			head=n;
			tail=n;
		}
		tail.setNext(n);
		tail=n;
		size++;
		
	}
	
	public int size(){
		return size;
	}
	
	public Iterator iterator(){
		return new LinkedListIterator();
	}
	
	private class LinkedListIterator implements Iterator{
		private Node node=head;//节点
		
		@Override
		public boolean hasNext() {
			if(node.getNext()==null) return false;
			else return true;
		}


		@Override
		public Object next() {
			Object o=node.getNext().getData();
			node=node.getNext();
			return o;
		}
		
	}
}

Node.java:
package cn.edu.hpu.iterator;


public class Node {
	private Object data;
	private Node next;
	
	
	public Node(Object data, Node next) {
		super();
		this.data = data;
		this.next = next;
	}
	
	public Object getData() {
		return data;
	}
	
	public void setData(Object data) {
		this.data = data;
	}
	
	public Node getNext() {
		return next;
	}
	
	public void setNext(Node next) {
		this.next = next;
	}
	
}

测试
LinkedListTest.java:
package cn.edu.hpu.iterator;


import cn.edu.hpu.iterator.LinkedList;


public class LinkedListTest {
	public static void main(String[] args) {
		Collection c=new LinkedList();
		for(int i=0;i<20;i++){
			c.add(new Cat(i));
		}
		System.out.println(c.size());
		
		LinkedList ll=(LinkedList)c;
		Iterator it=ll.iterator();
		while(it.hasNext()){
			Cat cat=(Cat)it.next();
			System.out.print(cat.getId()+" ");
		}
	}
}

测试结果:
20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 

程序运行正常,作业完成

转载请注明出处:http://blog.csdn.net/acmman/article/details/43924261

你可能感兴趣的:(设计模式,iterator,迭代器,遍历器)