我们可以在装箱后调用原始包装类作为引用类型吗?
我也知道 AtomicInteger
, AtomicLong
, AtomicBoolean
和 AtomicReference<V>
是可变的。
Integer age = new Integer(23);
Integer old = age;
System.out.println("Age : "+age);
System.out.println("Old : "+ old);
System.out.println("*************");
age = 24;
System.out.println("Age : "+age);
System.out.println("Old : "+ old);
结果
Age : 23
Old : 23
After update ****
Age : 24
Old : 23
我同意原语及其包装器是不可变的。 但是这里拳击的意义\目的是什么?
从维基百科复制:
Boxing, otherwise known as wrapping, is the process of placing a primitive type within an object so that the primitive can be used as a reference object.
最佳答案
如果您使用基元,您的程序将以相同的方式工作(第二个分配使用自动装箱,因此它不会改变任何东西)。包装器确实是引用类型,但您不能利用它,因为在 Java 中定义的原语的所有包装器类都是不可变的。
正因为如此,例如,您不能将包装的 int
发送到方法中,在那里修改它,并期望调用者看到原始包装器的修改。如果您需要此功能,则必须编写自己的可变包装器。
关于java - 澄清拳击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20636485/