【设计模式】Iterator设计作业-设计LinkedList的iterator
2015-02-24 09:34
232 查看
完成了上次迭代器设计的作业:http://blog.csdn.net/acmman/article/details/43920153
LinkedList也需要写一个iterator方法,返回一个实现了Iterator的对象。该如何写?
LinkedList.java:
Node.java:
测试
LinkedListTest.java:
测试结果:
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
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
相关文章推荐
- 设计模式(8) - 迭代器模式(iterator)- 实现ArrayList和linkedList的迭代器
- 简单模拟LinkedList-迭代器设计模式-马士兵设计模式教程 .
- 设计模式之Iterator——点名篇(原创)
- 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern)
- 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern)
- 设计模式之Prototype——作业篇
- 设计模式(22)-迭代器模式(Iterator)
- 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern)
- 设计模式简单代码之Iterator模式
- 设计模式简单代码之Iterator模式
- Iterator设计模式
- 设计模式之Prototype——作业篇
- .Net中的设计模式——Iterator模式
- 设计模式之Prototype——作业篇(原创)
- .Net中的设计模式——Iterator模式(对理解IEnumerable接口有帮助)
- 设计模式之Iterator——点名篇
- 设计模式学习(1)——Design Pattern List
- 用linked list 来理解Decorator 模式
- 设计模式与泡mm的关系之iterator迭代模式及再思考
- 设计模式之Iterator