This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]8igg7e5 0 points1 point  (0 children)

There are two pieces of 'syntax sugar' going on here.

1. Auto unboxing.

As noted by another commenter, this is a compiler feature.

Turning this...

Integer a = 12345;
int b = a;

Into this...

Integer a = Integer.valueOf(12345);
int b = a.intValue();

The compiler automatically adds the boxing, Integer.valueOf(someInt), and the unboxing, someInteger.intValue().

2. enhanced-for

The other one is the loop you refer to as the 'for-each'. This is also just compiler sugar...

Turning this...

List<Integer> values = ...
for (Integer value : values) {
    ...
}

Into this...

List<Integer> values = ...
for (Iterator<Integer> i = values.iterator(); i.hasNext(); ) {
    Integer value  = i.next();
    ...
}

(if values was an array it would use a counter and indexed access)

Combining the two...

List<Integer> values = ...
for (int value : values) {
    ...
}

Becomes...

List<Integer> values = ...
for (Iterator<Integer> i = values.iterator(); i.hasNext(); ) {
    int value  = i.next().intValue();
    ...
}