Java 1.5 Tiger A Developers Notebook [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Java 1.5 Tiger A Developers Notebook [Electronic resources] - نسخه متنی

David Flanagan, Brett McLaughlin

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید








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:


Integer counter = 1;
while (true) {
System.out.printf("Iteration %d%n", counter++);
if (counter > 1000) break;
}

The variable counter is treated just as an int in this code.


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.


This is actually an important pointthe ++ operator has not been changed to work with object wrapper typesit's only through autounboxing that this code works.

Once the value is unboxed, it is incremented. Then, the new value has to
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.


/ 131