我们可以把所有的包装类都称为不可变的吗?在这里,像String....so一样工作的整数在包装器类中有混淆
String s1 = "hi";
concatString(s1);
System.out.println(s1);
Integer i = 10;
changeInteger(i);
System.out.println(i);
private static void changeInteger(Integer i) {
i=i+10;
System.out.println(i);
}
private static void concatString(String s1) {
s1 = s1+"Bye";
System.out.println(s1);
}输出:hiBye hi 20 10
发布于 2016-02-25 22:33:07
是的,原始包装类和String是不可变的。我猜造成您困惑的原因是下面这行:
private static void changeInteger(Integer i) {
i=i+10;
....实际上,参数类型是Integer,看起来你可以通过添加1来改变它的值。实际上,在自动装箱之前,这一行看起来是这样的:
i = new Integer(i.intValue() + 1);这行代码从包装器中提取int值,添加1,然后将结果传递给Integer的构造函数,该构造函数创建Integer的新实例。
在java 5中引入的自动装箱是一种“编译器魔术”特性,它可以处理行。
i=i+10; 作为
i = new Integer(i.intValue() + 1);https://stackoverflow.com/questions/35630026
复制相似问题