4.3 Incrementing and Decrementing Wrapper Types
When you begin to think about the
implications of boxing and unboxing,
you'll realize that they are far-reaching. Suddenly, every operation available
to a primitive should be available to its wrapper-type counterpart,
and vice versa. One of the immediate applications is the increment and
decrement operations: ++ and --. Both of these operations now work for
wrapper types.
4.3.1 How do I do that?
Well, without much work, actually:
The variable counter is treated just as an int in this code.
Integer counter = 1;
while (true) {
System.out.printf("Iteration %d%n", counter++);
if (counter > 1000) break;
}
4.3.2 What just happened?
It's worth noting that more happened here than perhaps meets the eye.
Take this simple portion of the example code:
counter++
Remember that counter is an Integer. So the value in counter was first
auto-unboxed into an int, as that's the type required for the ++ operator.
|
be stored back in counter, which requires a boxing operation. All this in
a fraction of a second!You might also notice that the Integer value of counter was compared to
the literal, and therefore primitive, value 1000. This is just another example
of autounboxing at work.