I read this blog post and proceeded to complete the questions to see if I could answer them in under an hour.
One of the simple challenges is to sum the values in a List
using a while
loop. Simple enough but food for thought.
I present two methods below, one using an incremented index and the other using an Iterator
. Which solution is superior and why?
// Using an Iterator
public static int whileSummer(List<Integer> list) {
int sum = 0;
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
sum += iterator.next().intValue();
}
return sum;
}
// Using an incremented index
public static int whileSummer(List<Integer> list) {
int sum = 0;
int i = 0;
while (i < list.size()) {
sum += list.get(i).intValue();
i++;
}
return sum;
}
My personal opinion is that the argument is merely down to LOC, readability and instantiation overhead. What do you think?