Note that there are some explanatory texts on larger screens.

plurals
  1. POJava - remove() in custom iterator and linked list
    text
    copied!<p>I am an absolute Java beginner, and have been working on getting the remove() for a custom iterator (for a linked list) working. I have been trying for many hours getting this to work. My issue is that the iterated items are not removed. The method does however (correctly) throw an IllegalState-error, when there is no previous element.</p> <p>I would appreciate if you guys could have a look at it, and indicate what may be wrong, because I cannot work myself around it, and have tried all kinds of different things. One question: is the problem that I set next as head in constructor? Because if I don't, the list is not iterated at all! </p> <p>Thank you so much in advance.</p> <p>====================================================================</p> <pre><code>public class CustListIterator&lt;E&gt; implements Iterator&lt;E&gt; { private Node&lt;E&gt; head; private Node&lt;E&gt; next; private Node&lt;E&gt; prev; private CustList&lt;E&gt; list; public CustListIterator(CustList&lt;E&gt; list) { this.list = list; head = list.head; next = head; } public boolean hasNext() { return next != null; } public E next() { if (!hasNext()) throw new NoSuchElementException (); prev = next; E element = next.element; next = next.next; return element; } public void remove() { if(prev == null) { throw new IllegalStateException(); } else { if(prev == head){ head = prev.next; list.head = head; } next = prev.next; prev = null; list.listSize--; } } </code></pre> <p>=============================================================================</p> <p>Iteration of</p> <pre><code>CustList&lt;String&gt; items = new CustList&lt;String&gt;(); items.add("aaaaaa"); items.add("bbbbb"); items.add("ccc"); items.add("dddddddd"); items.add("eeeeee"); System.out.println("List iterated:"); Iterator&lt;String&gt; it = items.iterator(); while (it.hasNext()) { System.out.println(it.next()); it.remove(); } System.out.println("Size: " + items.size()); </code></pre> <p>=============================================================================</p> <p>Still gives however</p> <pre><code>List iterated: aaaaaa bbbbb ccc dddddddd eeeeee Size: 0 </code></pre>
 

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