0

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?

Robert Bain
  • 9,113
  • 8
  • 44
  • 63
  • 1
    http://stackoverflow.com/questions/1879255/performance-of-traditional-for-loop-vs-iterator-foreach-in-java DUPLICATE – Ya Wang May 13 '15 at 18:51
  • 2
    A linked list in the second method would have some performance loss. – panagdu May 13 '15 at 18:52
  • the superior solution is the one that will make your code more readable and scalable – svarog May 13 '15 at 18:53
  • For most instances I would believe that there is really no difference although I am sure one would be better at an extremely large number of elements. I don't know which one off hand. – wxkevin May 13 '15 at 18:53
  • One difference to note although a little off topic is that you cannot remove from the list using an iterator whereas you can with an index. – Maxqueue May 13 '15 at 18:54
  • 2
    @Maxqueue - false. You can use `iterator.remove()`. Removing by index is actually bad as it can mess up your looping logic – StormeHawke May 13 '15 at 18:57
  • yeah thanks stormhawke i was thinking of removing using for each loop. – Maxqueue May 13 '15 at 18:59

0 Answers0