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?
Boxing/unboxing has a cost at runtime.
Integer
once within the body of your loop, like you do, it won't make much of a difference.Integer
many times in the body of your loop, you would be better off unboxing it once with for(int i : ints)
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;
}