Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: Pass by reference / ListIterator.add()
    text
    copied!<p>Java doesn't pass variables by reference. In that case, how do data structures like <code>ListIterator</code> make changes to their corresponding list?</p> <p>Here is an example iterator I am writing:</p> <pre><code>public class OdpIterator&lt;E&gt; implements ListIterator&lt;E&gt; { private OdpList&lt;E&gt; list; private int cursor; public OdpIterator(OdpList&lt;E&gt; list) { this.list = list; } @Override public void add(E arg0) { list.add(arg0); } </code></pre> <p>But then when I try to change <code>list</code> through <code>add()</code>, it doesn't change the underlying list, so the following test fails:</p> <pre><code>OdpList&lt;Integer&gt; list = new OdpList&lt;Integer&gt;(); ListIterator&lt;Integer&gt; iter = list.listIterator(); iter.add(42); assertTrue(list.contains(42)); </code></pre> <p>OdpList add: I believe that it is correct, as it passes its unit tests.</p> <pre><code>@Override public boolean add(E arg0) { ListCell&lt;E&gt; cell = new ListCell&lt;E&gt;(arg0); if (size() &gt; 0) { //if something is already in the list tail.setNext(cell); tail = cell; } else { head = cell; tail = cell; } return true; } </code></pre> <p>ListCell constructor:</p> <pre><code>public class ListCell&lt;T&gt; { public ListCell(T arg0) { this.datum = arg0; next = null; } } </code></pre> <p>OdpList listIterator:</p> <pre><code>@Override public ListIterator&lt;E&gt; listIterator() { return new OdpIterator&lt;E&gt;(this); } </code></pre> <p>OdpList contains:</p> <pre><code>@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&lt;E&gt; o, Object search, int soFar) { if (o == null) { return -1; } if (o.getDatum() == null &amp;&amp; search != null) { return findAfter(o.getNext(), search, soFar + 1); } if ((o.getDatum() == null &amp;&amp; search == null) || o.getDatum().equals(search)) { return soFar; } return findAfter(o.getNext(), search, soFar + 1); } </code></pre> <p>How do I do this? Or am I misunderstanding how iterators work?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload