Java创建您自己的Iterable结构,以用于Iterator或for-each循环。
示例
为了确保可以使用迭代器或for-each循环对我们的集合进行迭代,我们必须注意以下步骤:
我们要迭代的内容必须是Iterable公开的iterator()。
java.util.Iterator通过覆盖设计hasNext(),next()并remove()。
我在下面添加了一个简单的通用链表实现,该实现使用上述实体使链表可迭代。
package org.algorithms.linkedlist;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<T> implements Iterable<T> {
Node<T> head, current;
private static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
}
}
public LinkedList(T data) {
head = new Node<>(data);
}
public Iterator<T> iterator() {
return new LinkedListIterator();
}
private class LinkedListIterator implements Iterator<T> {
Node<T> node = head;
@Override
public boolean hasNext() {
return node != null;
}
@Override
public T next() {
if (!hasNext())
throw new NoSuchElementException();
Node<T> prevNode = node;
node = node.next;
return prevNode.data;
}
@Override
public void remove() {
throw new UnsupportedOperationException("删除逻辑未实现。");
}
}
public void add(T data) {
Node current = head;
while (current.next != null)
current = current.next;
current.next = new Node<>(data);
}
}
class App {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>(1);
list.add(2);
list.add(4);
list.add(3);
//测试#1
System.out.println("u唱迭代器:");
Iterator<Integer> itr = list.iterator();
while (itr.hasNext()) {
Integer i = itr.next();
System.out.print(i + " ");
}
//测试#2
System.out.println("\n\nusing for-each:");
for (Integer data : list) {
System.out.print(data + " ");
}
}
}输出结果
u唱迭代器: 1 2 4 3 using for-each: 1 2 4 3
这将在Java7+中运行。您还可以通过以下方式使其在Java5和Java6上运行:
LinkedList<Integer> list = new LinkedList<>(1);
与
LinkedList<Integer> list = new LinkedList<Integer>(1);
或任何其他版本(通过合并兼容的更改)。