我知道这可能很愚蠢,但是很多地方声称Java中的Integer类是不可变的,但下面的代码:
Integer a=3;
Integer b=3;
a+=b;
System.out.println(a);执行时没有任何问题,给出了(预期的)结果6。因此,实际上a的值已经改变了。这不是意味着Integer是可变的吗?第二个问题和一些离题:“不可变的类不需要复制构造函数”。有人愿意解释一下原因吗?
发布于 2017-10-09 20:26:06
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1="Hi";
String s2=s1;
s1="Bye";
System.out.println(s2); //Hi (if String was mutable output would be: Bye)
System.out.println(s1); //Bye
Integer i=1000;
Integer i2=i;
i=5000;
System.out.println(i2); // 1000
System.out.println(i); // 5000
int j=1000;
int j2=j;
j=5000;
System.out.println(j2); // 1000
System.out.println(j); // 5000
char c='a';
char b=c;
c='d';
System.out.println(c); // d
System.out.println(b); // a
}输出为:
嗨,再见1000 5000 1000 5000 d a
因此char是可变的,String Integer和int是不可变的。
https://stackoverflow.com/questions/5560176
复制相似问题