Java 不通过引用传递变量。在那种情况下,数据结构如何ListIterator
更改其对应的列表?
这是我正在编写的示例迭代器:
public class OdpIterator<E> implements ListIterator<E> {
private OdpList<E> list;
private int cursor;
public OdpIterator(OdpList<E> list) {
this.list = list;
}
@Override
public void add(E arg0) {
list.add(arg0);
}
但是当我尝试更改list
时add()
,它不会更改基础列表,因此以下测试失败:
OdpList<Integer> list = new OdpList<Integer>();
ListIterator<Integer> iter = list.listIterator();
iter.add(42);
assertTrue(list.contains(42));
OdpList add:我相信它是正确的,因为它通过了单元测试。
@Override
public boolean add(E arg0) {
ListCell<E> cell = new ListCell<E>(arg0);
if (size() > 0) { //if something is already in the list
tail.setNext(cell);
tail = cell;
}
else {
head = cell;
tail = cell;
}
return true;
}
ListCell 构造函数:
public class ListCell<T> {
public ListCell(T arg0) {
this.datum = arg0;
next = null;
}
}
OdpList 列表迭代器:
@Override
public ListIterator<E> listIterator() {
return new OdpIterator<E>(this);
}
OdpList 包含:
@Override
public boolean contains(Object arg0) {
return indexOf(arg0) == -1;
}
@Override
public int indexOf(Object arg0) {
return findAfter(head, arg0, 0);
}
private int findAfter(ListCell<E> o, Object search, int soFar) {
if (o == null) {
return -1;
}
if (o.getDatum() == null && search != null) {
return findAfter(o.getNext(), search, soFar + 1);
}
if ((o.getDatum() == null && search == null) || o.getDatum().equals(search)) {
return soFar;
}
return findAfter(o.getNext(), search, soFar + 1);
}
我该怎么做呢?还是我误解了迭代器的工作原理?