On Thu, 21 Dec 2006 20:40:45 -0000, Daniel Pitts
<> wrote:
> Java 1.5 finaly gave us an elegant for each construct, but for-each
> lacks the ability to manipulate the underlying Iterable structure.
>
> Generally, the way to do this is (in pseudo-code
>
> Obtain the iterator.
> L: Check if it has a next element
> get the next element
> process the element.
> repeat from L
>
> This can be coded in Java a few ways.
> // For method:
> for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext(); )
> {
> E e = iterator.next();
> if (shouldRemove(e)) {
> iterator.remove(e);
> }
> }
>
> // vs
> // While method:
> Iterator<E> iterator = iterable.iterator();
> while (iterator.hasNext()) {
> E e = iterator.next();
> if (shouldRemove(e)) {
> iterator.remove(e);
> }
> }
>
> Both approaches have their pros and cons, but I'm interested to see
> what people think.
>
> I'll post my opinion later.
The for loop is one line shorter but I've always preferred the while
loop. It justs seems more natural and more readable to me. When I was at
school, programming in BASIC and Pascal with less flexible for loops, for
loops were for a fixed number of iterations known at the start, and while
loops for an indeterminate number of iterations. With an iterator, you
don't know how many iterations are required until you've finished (you can
find out, but it's more work). So reading code that says "while there are
more elements do x" just seems more correct.
Dan.
--
Daniel Dyer
http://www.uncommons.org