Search code examples
javagenericscollectionsboxingunboxing

foreach loop by primitive or by boxed class in Java


Currently I am reading a book "Java Generics and Collections" and I have found an interesting code:

List<Integer> ints = Arrays.asList(1,2,3);
int s = 0;
for (int n : ints) { s += n; }
assert s == 6;

Here foreach loop iterate over primitives:

for (int n : ints) { ... }

However, Eclipse IDE suggests me to iterate over boxed type:

for (Integer n : ints) { ... }

Are there any benefits of using one or another style of iterating?


Solution

  • Boxing/unboxing has a cost at runtime.

    • if you are going to unbox the Integer once within the body of your loop, like you do, it won't make much of a difference.
    • if you unbox the Integer many times in the body of your loop, you would be better off unboxing it once with for(int i : ints)
    • if you are going to use an Integer in the body of your loop, then using int would lead to an unnecessary unbox/box operation.

    For example:

    List<Integer> subList = new ArrayList<>();
    
    for (Integer i : ints) { //better not to unbox
      if (someCondition(i)) subList.add(i);
    }
    
    for (int i : ints) { //better to unbox once
      int a = i;
      int b = 2 * i;
      sum += a + b - i;
    }