我需要编写一个实现Iterable接口的类。我对返回迭代器对象的含义感到困惑。迭代器只是遍历列表元素,那么我应该返回一个可迭代的列表还是其他什么?当迭代器仅仅是遍历或更改其他对象中的数据时,如何将其作为对象返回呢?
以下是一个非常简单的列表的示例。它将列表表示为链接元素。
迭代器对象作为匿名内部类创建,保留当前元素作为状态。每次调用iterator()
都会创建一个新的迭代器对象。
import java.util.Iterator;
public class SimplisticList<T> implements Iterable<T> {
/*
* A list element encapsulates a data value and a reference to the next
* element.
*/
private static class Element<T> {
private T data;
private Element<T> next;
Element(T data) {
this.data = data;
next = null;
}
public T getData() {
return data;
}
public Element<T> getNext() {
return next;
}
public void setNext(Element<T> next) {
this.next = next;
}
}
// We only need a reference to the head of the list.
private Element<T> first = null;
// The list is empty if there is no first element.
public boolean isEmpty() {
return first == null;
}
// Adding a new list element.
// For an empty list we only have to set the head.
// Otherwise we have to find the last element to add the new element.
public void add(T data) {
if(isEmpty()) {
first = new Element<T>(data);
} else {
Element<T> current = first;
while(current.getNext() != null) {
current = current.getNext();
}
current.setNext(new Element<T>(data));
}
}
@Override
public Iterator<T> iterator() {
// Create an anonymous implementation of Iterator<T>.
// We need to store the current list element and initialize it with the
// head of the list.
// We don't implement the remove() method here.
return new Iterator<T>() {
private Element<T> current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
T result = null;
if(current != null) {
result = current.getData();
current = current.getNext();
}
return result;
}
@Override
public void remove() {
// To be done ...
throw new UnsupportedOperationException();
}
};
}
}
返回迭代器意味着返回一个实现Iterator接口的类的实例。这个类必须实现hasNext()
、next()
和remove()
方法。该类的构造函数应以一种初始化实例的方式,使得next()
方法返回正在迭代的数据结构的第一个元素(如果不为空)。
Iterator
只能使用一次。一个 Iterable
可以生成多个 Iterator
。通常你需要实现两个。 - Louis WassermanhasNext()
、next()
和remove()
只允许您向前遍历您正在迭代的内容。 - Louis WassermanString[]
数组:public class MyIterator implements Iterator<String> {
private String[] arr;
private int index;
public MyIterator(String[] arr) {
this.arr = arr;
this.index = 0;
}
public boolean hasNext() {
return index < arr.length;
}
public String next() {
return arr[index++];
}
}
你还需要使用remove()
,但那只会抛出异常。请注意,当你使用new MyIterator(myStringArray)
构造这些迭代器之一时,你构造了一个具有对数组的引用的对象。 这个Iterator
不会是数组本身或其任何部分,但它有一个私有变量引用它。列表或其他数据结构(甚至不是数据结构的东西)的Iterator
将遵循类似的模式。
ArrayList
迭代器的源代码。 - chrylis -cautiouslyoptimistic-Iterator
并不意味着你会“返回一个列表”,而是你返回的对象,该对象将实现Iterator
,很可能具有私有变量,这些变量引用列表或引用列表的元素。 - ajb