2

I'm doing a Java implementation for a Doubly-linked list.

I have some methods like this:

private DLNode<T> getNodeAtPosition(int position) throws DLListException {
  verifySize(this.listSize(), position);
  DLNode<T> result = this.first;
  for (int counter = 0; counter < position; counter++) { // <=======
    result = result.next;
  }
  return result;
}

It can be done either with for/while loops or with iterators. Which one optimizes those methods? That's a important thing if you're trying to do a very used ADT.

I'm not meaning for-each loops, I mean loops where you have to stop before the end as this one, or generally any loop that has more than one termination condition.

CarlosMorente
  • 775
  • 1
  • 7
  • 17

1 Answers1

2

Should I use iterators instead of for/while loops? (In this situation where the loop has more than one termination condition.)

(My postscript above)

That's primarily a matter of opinion, but if the simple for loop does what you want, avoiding the overhead of creating an Iterator object and calling its methods seems a reasonably objective reason for sticking with the simple for loop. Less for the JVM's JIT to optimize, particularly if you're writing a utility class that will be used in lots of places (e.g., a doubly-linked list).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • So you mean that if I want to optimize it, it will be better with an iterator, but in any other case it's better to avoid it, right? – CarlosMorente Apr 20 '15 at 15:08
  • 1
    @CarlosMorenteLozano: No, I mean that if a `for` loop does what you need, then you can avoid the JVM having to optimize creating the iterator and calling its methods -- by just using a `for` loop instead. – T.J. Crowder Apr 20 '15 at 15:09