主要是分工作业。Iterable告知这个集合可以直接进行遍历;Iterator则是执行具体的遍历操作。而且一个实现Iterable接口的集合可以进行多次的遍历,当每次执行遍历操作的时候把自己本身传给实现Iterator的对象,这样每次遍历的操作都不会影响这个集合的内部元素。
package com.zz.iterator;
public class LinkedList<E> implements Collection<E> , Iterable<E>{
private int size = 0;
private Node<E> head;
private Node<E> tail;
public Node<E> getHead() {
return head;
}
public void setHead(Node<E> head) {
this.head = head;
}
public Node<E> getTail() {
return tail;
}
public void setTail(Node<E> tail) {
this.tail = tail;
}
public void add(E e) {
Node<E> n = new Node<E>(e,null);
if (head == null) {
head = n;
tail = n;
} else {
tail.setNext(n);
tail = n;
}
size ++;
}
public E get(int ix) throws IndexOutOfBoundsException{
if (size <= 0 || size <= ix) {
throw new IndexOutOfBoundsException("数组越界了:"+ix);
}
Node<E> e = head;
for (int i=0;i<ix;i++) {
e = e.getNext();
}
return e.getCurrentE();
}
public int size() {
return size;
}
@Override
public Iterator<E> iterator() {
return new LinkedListIterator<E>(this);
}
@SuppressWarnings("hiding")
public class LinkedListIterator<E> implements Iterator<E> {
private int index = 0;
private LinkedList<E> linkedList;
public LinkedListIterator(LinkedList<E> linkedList) {
this.linkedList = linkedList;
}
@Override
public boolean hasNext() {
return size > index;
}
@Override
public E next() {
Node<E> node = linkedList.getHead();
for (int i=0;i<index;i++) {
node = node.getNext();
}
index ++;
return node.getCurrentE();
}
}
}