整数是不可改变的 [英] Is Integer Immutable
问题描述
我知道这可能是非常愚蠢的,但很多地方声称Java中的Integer类是不可变的,但是代码如下:
I know this is probably very stupid, but a lot of places claim that the Integer class in Java is immutable, yet the following code:
Integer a=3;
Integer b=3;
a+=b;
System.out.println(a);
执行(预期)结果时没有任何问题6.因此,a的值已经有效地改变了。这不意味着Integer是可变的吗?
次要问题和一些小问题:不可变类不需要复制构造函数。有人在乎解释原因吗?
Executes without any trouble giving the (expected) result 6. So effectively the value of a has changed. Doesn't that mean Integer is mutable? Secondary question and a little offtopic: "Immutable classes do not need copy constructors". Anyone care to explain why?
推荐答案
不可变并不意味着 a
永远不能等于另一个价值。例如, String
也是不可变的,但我仍然可以这样做:
Immutable does not mean that a
can never equal another value. For example, String
is immutable too, but I can still do this:
String str = "hello";
// str equals "hello"
str = str + "world";
// now str equals "helloworld"
那么那里发生了什么?由于 String
是不可变的,所以显然 str
没有改变。但它现在等于不同的东西。这是因为 str
现在是一个完全新实例化的对象,就像你的 Integer
一样。所以 a
的值没有变异,但它被一个全新的对象所取代,即 new Integer(6)
。
So what happened there? Since String
is immutable, clearly str
was not changed. But it now equals something different. This is because str
is now a completely newly instantiated object, just as your Integer
is. So the value of a
did not mutate, but it was replaced with a completely new object, i.e. new Integer(6)
.
这篇关于整数是不可改变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!