首页 > 学院 > 开发设计 > 正文

Java-马士兵设计模式学习笔记-迭代器模式-模仿Collectin ArrayList LinckedList

2019-11-15 00:36:14
字体:
来源:转载
供稿:网友
java-马士兵设计模式学习笔记-迭代器模式-模仿Collectin ArrayList LinckedList

Java Iterator模式Java Iterator模式, 模仿Collectin ArrayList LinckedList

一、有如下几个类

1.接口Collection.java

2.接口Iterator.java

3.ArrayList.java

4.LinkedList.java

5.Node.java

关系如下:

代码如下:

1.接口Collection.java

public interface Collection<E> {public void add(E e);public int size();public Iterator iterator();}

  

2.ArrayList.java

public class ArrayList<E> implements Collection<E>{//先给定一个长度为10的数组Object [] objects = new Object[10];//冗余一个int指数,方便判定是组是否为满和返回集合大小int index = 0;@Override//1.动态添加元素public void add(E e) {//1.1先判断数组是否已满if(index == objects.length){Object [] newObjects = new Object[objects.length*2];System.arraycopy(objects, 0, newObjects, 0, objects.length);objects = newObjects;//数组是引用数据类型}//1.2为新添加的元素指定下标objects[index] = e;//1.3index自加1,以方便返回集合在大小index++;}//2.根据下标访问元素@Override//3.返回集合大小public int size() {return index;}@Overridepublic Iterator iterator() {return new ArrayListIterator();}PRivate class ArrayListIterator implements Iterator {private int currentIndex = 0;@Overridepublic Object next() {// 返回最下一个元素Object o = objects[currentIndex];currentIndex++;return o;}@Overridepublic boolean hasNext() {// 判断是否为最后一个元素if(currentIndex >= index){return false;}return true;}}}

  

3.LinkedList.java

public class LinkedList<E> implements Collection<E> {private Node head;private Node tail;private int size;public void add(E e){Node n = new Node(e, null);if(head == null){head = n;tail = n;size++;} else {tail.setNext(n);tail = n;size++;}}public int size(){return size;}@Overridepublic Iterator iterator() {return new LinkedListIterator();}private class LinkedListIterator implements Iterator {private Node currentNode = head;@Overridepublic Object next() {Object o = currentNode.getData();currentNode = currentNode.getNext();return o;}@Overridepublic boolean hasNext() {if(currentNode.getNext() == null){return false;}return true;}}}

4.Node.java

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;}}

5.Iterator.java

public interface Iterator {public Object next();public boolean hasNext();}

6.Dog.java

public class Dog {private int id;public Dog(int id) {super();this.id = id;}@Overridepublic String toString() {return "Dog"+id;}}

7.测试类CollectionTest.java

public class CollectionTest {@Testpublic void test() {Collection co = new LinkedList();for(int i = 0 ;i < 15 ;i++){co.add(new Dog(i));}System.out.println(co.size());Iterator it = co.iterator();while(it.hasNext()){System.out.println(it.next());}}}

运行结果


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表