理解:Iterator提供了对容器的遍历,有next(),hashnext(),remove()等方法。

模拟jdk中容器的遍历:

//调用程序

public class Test {public static void main(String[] args) {collection l = new LinkList();for(int i = 0; i < 15; i++) {l.add(new Car(i));}System.out.println(l.size());Iterator i = l.iterator();while(i.hashNext()){Object o =i.next();System.out.println(o.toString());}}

//collection接口,和Iterator接口

public interface collection {void add(Object o);int size();Iterator iterator();}
public interface Iterator {Object next();boolean hashNext();}

//链式存储

public class LinkList implements collection {Node head;Node tail;int index = 0;public void add(Object o) {Node n = new Node(o, null);if (index == 0) {head = n;tail = n;}tail.setNext(n);tail = n;index++;}@Overridepublic Iterator iterator() {return (Iterator) new LinkListIterator();}@Overridepublic int size() {return index;}private class LinkListIterator implements Iterator {@Overridepublic boolean hashNext() {if (head == null)return false;elsereturn true;}@Overridepublic Object next() {Object o = head.getData();head = head.getNext();return o;}}}

//链式对象

 

public class Node {private Object data;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;}public Node(Object data, Node next) {super();this.data = data;this.next = next;}private Node next;}

//数组存储

public class ArrayList implements collection {Object[] objects = new Object[10];int index = 0;public void add(Object o) {if (index == (objects.length)) {Object[] newob = new Object[objects.length * 2];System.arraycopy(objects, 0, newob, 0, objects.length);objects = newob;}objects[index] = o;index++;}public int size() {return index;}@Overridepublic Iterator iterator() {return new ArrayListIterator();}private class ArrayListIterator implements Iterator {private int currentsize = 0;@Overridepublic boolean hashNext() {if (currentsize >= index)return false;elsereturn true;}@Overridepublic Object next() {return objects[currentsize++];}}}

总结:

1.内部类的运用

2.用数组和链表模拟容器

3.接口较细比较好