我知道这可能很愚蠢,但是很多地方声称Java中的Integer类是不可变的,但下面的代码:
Integer a=3;
Integer b=3;
a+=b;
System.out.println(a);执行时没有任何问题,给出了(预期的)结果6。因此,实际上a的值已经改变了。这不是意味着Integer是可变的吗?第二个问题和一些离题:“不可变的类不需要复制构造函数”。有人愿意解释一下原因吗?
发布于 2011-04-06 08:35:09
不可变并不意味着a永远不能等于另一个值。例如,String也是不可变的,但我仍然可以这样做:
String str = "hello";
// str equals "hello"
str = str + "world";
// now str equals "helloworld"str没有改变,相反,str现在是一个全新实例化的对象,就像您的Integer一样。因此,a的值并没有发生变化,而是被一个全新的对象所取代,即new Integer(6)。
发布于 2011-04-06 08:32:14
a是对一些Integer(3)的“引用”,你的速记a+=b实际上意味着这样做:
a = new Integer(3 + 3)所以,整数不是可变的,但是指向它们的变量是*。
*可以有不可变的变量,这些变量由关键字final表示,这意味着引用可能不会改变。
final Integer a = 3;
final Integer b = 3;
a += b; // compile error, the variable `a` is immutable, too.发布于 2011-04-06 14:46:14
您可以使用System.identityHashCode()确定对象是否已更改(更好的方法是使用普通的==,但是不太明显的是引用而不是值发生了更改)
Integer a = 3;
System.out.println("before a +=3; a="+a+" id="+Integer.toHexString(System.identityHashCode(a)));
a += 3;
System.out.println("after a +=3; a="+a+" id="+Integer.toHexString(System.identityHashCode(a)));打印
before a +=3; a=3 id=70f9f9d8
after a +=3; a=6 id=2b820dda你可以看到a引用的对象的底层"id“已经改变了。
https://stackoverflow.com/questions/5560176
复制相似问题