private class MyIterator implements Iterator<T> { private int index; // to track position public boolean hasNext() { return index < MyIterableArrayList.this.size(); } public T next() { if (hasNext()) return MyIterableArrayList.this.getEntry(index++); else throw new NoSuchElementException("illegal call to " + getClass().getName() + ".MyIterator.next"); } public void remove() { throw new UnsupportedOperationException(getClass().getName() + ".MyIterator.remove is not supported"); } } public Iterator<T> iterator() { return new MyIterator(); }
private class MyIterator implements Iterator<T> { private Node p; // to track position private MyIterator() { p = head; } public boolean hasNext() { return p != null; } public T next() { if (hasNext()) { T value = p.value; p = p.next; return value; } else throw new NoSuchElementException("illegal call to " + getClass().getName() + ".MyIterator.next"); } public void remove() { throw new UnsupportedOperationException(getClass().getName() + ".MyIterator.remove is not supported"); } } public Iterator<T> iterator() { return new MyIterator(); }
Node prev = ... // insert after this node, null if index=0 or list is empty Node p = ... // insert before this node node, null if empty list or adding to end // create new node at current position currentNode = ... currentNode.value = ... currentNode.next = p; // possibly null currentNode.prev = prev; // possibly null currentIndex = index; // manage the "next" link and "head" if (prev == null) head = currentNode; else prev.next = currentNode; // manage the "prev" link and "tail" if (p == null) tail = currentNode; else p.prev = currentNode;
Node prev = ... // the node before the node to be removed, null if index=0 Node p = ... // the node after the node to be removed, null if removing to end // manage the "next" link and "head" if (prev == null) head = p; else prev.next = p; // manage the "prev" link and "tail" if (p == null) tail = prev; else p.prev = prev; // reset current position because currentNode is going away if (p == null) // move towards head if tail got removed { currentNode = prev; // possibly null if only remaining node got removed --currentIndex; // possibly -1 (but ignored because currentNode is null) } else currentNode = p; // currentIndex is unchanged
[ Home | Contact Prof. Burns ]