我必须编写一个实现Iterable接口的类。我对返回迭代器对象的含义感到困惑。迭代器只是遍历列表的元素,那么我如何将其作为对象返回?我会返回一个能够迭代的列表吗?当迭代器完成所有操作时,它如何成为对象?或者更改其他对象中的数据?
答案 0 :(得分:2)
返回迭代器意味着返回实现Iterator接口的类的实例。该课程必须实施hasNext()
,next()
和remove()
。该类的构造函数应该以{{1}}将返回您正在迭代的数据结构的第一个元素(如果它不为空)的方式初始化实例。
答案 1 :(得分:2)
这是一个非常简单的列表示例。它将列表表示为链接元素。
迭代器对象被创建为一个匿名内部类,将当前元素保存为状态。每次调用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();
}
};
}
}
答案 2 :(得分:1)
这是一个通过String[]
数组的迭代器的简单示例:
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
将遵循类似的模式。