Я запутался в autoboxing unboxing в java. Пожалуйста, см. Мои следующие два прогарма.
Integer x = 400;
Integer y = x;
x++; x--;
System.out.println((x==y));
The output is false.
I known why the output is false. Because of autoboxing x.
Integer x = 100;
Integer y = x;
x++; x--;
System.out.println((x==y));
The output is true.
But the program is same as the upper. Why the output is true?
Please explain me detail.
Большое спасибо.
Это связано с тем, что целые -128 до 127 кэшируются, поэтому во втором примере x и y относятся к одному и тому же экземпляру Integer.
Integer x = 100; // x refers to cached 100
x++;
эквивалентно
int var = x.intValue();
var++;
x = Integer.valueOf(var); // returns cached 100
См. API Integer.valueOf(int).