Java中迭代器的实现
程序员文章站
2022-05-03 18:05:12
...
此处用链表来示范
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;
}
}
上一篇: 网络爬虫day02
下一篇: Zepto中如何实现"变量"的类型判断