Java包装器类真的是不可变的吗? [英] Are Java wrapper classes really immutable?
本文介绍了Java包装器类真的是不可变的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Java包装器类应该是不可变的.这意味着一旦创建了对象,例如
Java Wrapper classes are supposed to be immutable. This means that once an object is being created, e.g.,
Integer i = new Integer(5);
其值不能更改.但是,做
its value cannot be changed. However, doing
i = 6;
是完全有效的.
那么,在这种情况下,不变性是什么意思?这与自动装箱/拆箱有关吗?如果是这样,有什么办法可以防止编译器执行此操作?
So, what does immutability in this context mean? Does this have to do with auto-boxing/unboxing? If so, is there any way to prevent the compiler from doing it?
谢谢
推荐答案
i
是参考.您的代码将引用 i
更改为指向另一个相同的,不变的 Integer
.
i
is a reference. Your code change the reference i
to point to a different, equally immutable, Integer
.
final Integer i = Integer.valueOf(5);
可能会更有用.
这篇关于Java包装器类真的是不可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文