此處用鏈表來示範
1.先創建一個鏈表類
public class LinkedList<T> implements Iterable<T> {
private Node<T> head;
private Node<T> tail;
public static <T> LinkedList<T> newEmptyList() {
return new LinkedList<T>();
}
private LinkedList() {
head = null;
tail = null;
}
public void add(T value) {
Node<T> node = new Node<>(value);
if (tail == null) {
head = node;
} else {
tail.setNext(node);
}
tail = node;
}
}
class Node<T> {
private final T value;
private Node next;
public Node(T value) {
this.value = value;
this.next = null;
}
public T getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
2.我們給LinkedList類實現Iterable<T>
接口
然後實現其方法
@Override
public Iterator<T> iterator() {
return null;
}
3.新建內部類並且實現Iterator<T>
接口
private class ListIterator implements Iterator<T> {
private Node<T> currentNode;
public ListIterator(Node<T> head) {
currentNode = head;
}
@Override
public boolean hasNext() {
return currentNode != null;
}
@Override
public T next() {
if (currentNode == null) {
throw new NoSuchElementException();
}
T value = currentNode.getValue();
currentNode = currentNode.getNext();
return value;
}
@Override
public void remove() {
}
}
此處只實現了next和hasNext,remove可自行實現,我們可以看到,迭代器其實就是對數據進行了封裝,使得每次可以獲取一個數據。
4.將此內部類返回
@Override
public Iterator<T> iterator() {
return new ListIterator(head);
}
5.最終代碼
package cn.chenmixuexi;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<T> implements Iterable<T> {
private Node<T> head;
private Node<T> tail;
public static <T> LinkedList<T> newEmptyList() {
return new LinkedList<T>();
}
private LinkedList() {
head = null;
tail = null;
}
public void add(T value) {
Node<T> node = new Node<>(value);
if (tail == null) {
head = node;
} else {
tail.setNext(node);
}
tail = node;
}
private class ListIterator implements Iterator<T> {
private Node<T> currentNode;
public ListIterator(Node<T> head) {
currentNode = head;
}
@Override
public boolean hasNext() {
return currentNode != null;
}
@Override
public T next() {
if (currentNode == null) {
throw new NoSuchElementException();
}
T value = currentNode.getValue();
currentNode = currentNode.getNext();
return value;
}
@Override
public void remove() {
}
}
@Override
public Iterator<T> iterator() {
return new ListIterator(head);
}
}
class Node<T> {
private final T value;
private Node next;
public Node(T value) {
this.value = value;
this.next = null;
}
public T getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}