我想实现一个Fail-Fast Iterator来从我自己的List中删除Entrys并测试它的正确行为。 List包含MyEntry类型的元素。
这些Entrys持有通用值和对下一个条目的引用。
class MyEntry<E> {
MyEntry<E> next;
E o;
MyEntry() {
this(null, null);
}
MyEntry(E o) {
this(o, null);
}
MyEntry(E o, MyEntry<E> e) {
this.o = o;
this.next = e;
}
}
List本身使用pos Entry跟踪其位置,其行为类似于Stack。现在我想实现一个快速失败的迭代器,它允许我迭代List并删除Entrys而不是抛出UnsupportedOperation异常。
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyList<E> implements Cloneable, java.lang.Iterable {
private MyEntry<E> begin;
private MyEntry<E> pos;
public MyList() {
pos = begin = new MyEntry<E>();
}
public boolean empty() {
return begin.next == null;
}
public boolean endpos() {
return pos.next == null;
}
public void reset() {
pos = begin;
}
/**
* Advances one step in this List.
*
* @throws NoSuchElementException if the last Entry of this List already has been reached.
*/
public void advance() {
if (endpos()) {
throw new NoSuchElementException("Already at the end of this List");
}
pos = pos.next;
}
/**
* Returns the actual element of this List.
*
* @return the actual element
* @throws RuntimeException if the last Entry of this List already has been reached.
*/
public E elem() {
if (endpos()) {
throw new NoSuchElementException("Already at the end of this List");
}
return pos.next.o;
}
/**
* Inserts <code>o</code> in this List. It will be placed before the actual
* element. After insertion the inserted element will become the actual
* element.
*
* @param x the element to be inserted
*/
public void add(E x) {
MyEntry<E> newone = new MyEntry<E>(x, pos.next);
pos.next = newone;
}
/**
* Deletes the actual element of this List. The element after the actual
* element will become the new actual element.
*
* @throws NoSuchElementException if the last Entry of this List already has been reached.
*/
public void delete() {
if (endpos()) {
throw new NoSuchElementException("Already at the end of this List");
}
pos.next = pos.next.next;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private MyEntry<E> it = null;
@Override
public boolean hasNext() {
return pos != null;
}
@Override
public E next() {
if (it==null)
it = begin;
else
it = it.next;
return it.o;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
我也已经尝试将Iterator实现到我的List并使用我的测试类
进行测试public class MyListTest {
@Test
public void test() {
MyList list = new MyList();
list.add("a");
list.add("b");
list.add("c");
while(list.iterator().hasNext()==true) {
System.out.println(list);
}
list.iterator().remove();
while(list.iterator().hasNext()==true) {
System.out.println(list);
}
}
}
但输出循环一个c,甚至没有删除一个条目。
我现在停留在快速失败迭代器的正确实现上,它可以遍历MyList并删除Entrys。因为我无法将其分解为单个问题,所以当我尝试实现迭代器时,我列出了一些问题