Re: looping through a list, starting at 1
On 8/1/2011 8:50 PM, Eric Sosman wrote:
On 8/1/2011 6:45 PM, Stefan Ram wrote:
Assuming a list has a sufficient number of entries at run
time, what should be prefered to assign a reference to each
entry to ?e?, starting at index 1:
for( final E e : l.sublist( 1, l.size() ))...
or
for( int i = 1; i< l.size(); ++i ){ final E e = l.get( 0 ); ... }
(ITYM l.get(i)?)
How about
Iterator<E> it = l.iterator();
it.next(); // ignore element 0
while (it.hasNext()) {
E e = it.next();
...
}
In short, there may well be half-a-dozen ways to do what you ask,
if not more. None of them stands out as "preferred" to my eye;
you may as well do whatever seems natural.
To add yet another option, if you are writing lots of iterations over
the "tail" of a collection, then you could define an Iterable wrapping
class, like this:
public class Tail<T> implements Iterable<T> {
public static <T> Tail<T> tail(final Iterable<T> coll) {
return new Tail<T>(coll);
}
public Iterator<T> iterator() {
return iter;
}
private Iterator<T> iter;
private Tail(final Iterable<T> coll) {
iter = coll.iterator();
if (iter.hasNext()) iter.next();
}
}
then to use
import static utils.Tail.tail;
...
for (final E e : tail( list )) {
...
}