【设计模式】Iterator设计作业-设计LinkedList的iterator
来源:互联网 发布:apache http有什么用 编辑:程序博客网 时间:2024/06/06 05:32
完成了上次迭代器设计的作业: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
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;//节点@Overridepublic boolean hasNext() {if(node.getNext()==null) return false;else return true;}@Overridepublic 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
0 0
- 【设计模式】Iterator设计作业-设计LinkedList的iterator
- 设计模式--Iterator模式
- 设计模式---Iterator模式
- 设计模式--Iterator 模式
- 【设计模式】Iterator模式
- Java Iterator的设计模式
- 设计模式之Iterator
- Iterator设计模式
- Iterator设计模式
- 设计模式之Iterator
- 设计模式之 iterator
- 设计模式 -- Iterator(迭代器)
- Iterator设计模式
- Iterator设计模式
- Iterator------设计模式
- 设计模式 Iterator
- 设计模式之Iterator
- 设计模式Iterator
- swift与OC之间不得不知道的21点
- Windows7 旗舰版睡眠后不能唤醒
- 第六章 一张白纸好作画—Canvas画布(5)
- 初学Android,WebView
- C Language Study - 错误的指针初始化方式
- 【设计模式】Iterator设计作业-设计LinkedList的iterator
- Cobbler添加自定义 YUM 源
- 我的CSDN历程[图]
- gSpan频繁子图挖掘算法
- udev
- Eclipse 单体测试
- 【JavaScript】JavaScript的数组剖析
- c++ templates
- linux 切换用户身份、su、sudo、/etc/sudoers