What are the exact operations that the extended for-loop does in the linked list for each iteration?

for (String msg : messages) {
    System.out.println(msg);
}

      

Say messages are a properly initialized circular, doubly linked list that doesn't have a head or end (link) pointer. That is, it has a current node pointer. My question is just what exactly is the improved loop for each iteration. If needed, I have an interface that I can post to this special type of ADT that the messages are.

Here's an iterator:

import java.util.*;
public class LinkedCircularSequenceIterator<E> implements Iterator<E> {
     private DblListnode<E> curr;
     private int itemsLeft;

  public LinkedCircularSequenceIterator(DblListnode<E> curr, int numItems) {
    this.curr = curr;
    this.itemsLeft = numItems;
  }

  public boolean hasNext() {
    return itemsLeft > 1;
  }

  public E next() {
    if(!hasNext()) {
        throw new NoSuchElementException();
    }
    curr = curr.getNext();
    itemsLeft--;

    return curr.getPrev().getData();
  }

  public void remove() {
    throw new UnsupportedOperationException();
  }
}

      

+3


source to share


2 answers


It should do something like



Iterator<Message> iter = messages.iterator();
while (iter.hasNext()){
    msg=iter.next().toString();
    System.out.println(msg);
}

      

+3


source


The improved for-loop does nothing special. a

for (T i : aCollection) {
  doSomething;
}

      

just translates into



for (Iterator<T> itr = aCollection.iterator(); itr.hasNext(); ) {
  T i = itr.next();
  doSomething;
}

      

How it iterates through the collection is the job of the iterator and has nothing to do with an extended loop.

+3


source







All Articles