Java doesn't pass variables by reference. In that case, how do data structures like ListIterator
make changes to their corresponding list?
Here is an example iterator I am writing:
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);
}
But then when I try to change list
through add()
, it doesn't change the underlying list, so the following test fails:
OdpList<Integer> list = new OdpList<Integer>();
ListIterator<Integer> iter = list.listIterator();
iter.add(42);
assertTrue(list.contains(42));
OdpList add: I believe that it is correct, as it passes its unit tests.
@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 constructor:
public class ListCell<T> {
public ListCell(T arg0) {
this.datum = arg0;
next = null;
}
}
OdpList listIterator:
@Override
public ListIterator<E> listIterator() {
return new OdpIterator<E>(this);
}
OdpList contains:
@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);
}
How do I do this? Or am I misunderstanding how iterators work?