java中String、Integer等包装类有一个共性问题,就是他们实际上是使用对应的基本数据类型来存放数据的。例如String类使用char[]来储存数据的,Integer使用int来存的。又因为char、int等基本数据类型作为形参时,函数就不会改变他们的值。所以String、Integer等这些包装类在作为形参传递给函数时,函数同样不会改变实参的值。举个例子:
public class test {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Integer a=1;
b(a);
System.out.println(a);
a=new Integer(3);
System.out.println(a);
}
static void b(Integer i)
{
i=2;
}
}
先实例化一个Integer对象,值设置为1,我们先试图通过函数将他的值改为2。然后再重新给他实例化为3。输出结果为:
我们发现,第一次用函数并没有改变他的值,重新实例化后他的值才发生改变,验证了我们上面的观点。再举个例子:
public static void main(String[] args) {
String s="123";
b(s);
System.out.println(s);
s="456";
System.out.println(s);
s=new String("789");
System.out.println(s);
}
static void b(String i)
{
i="456";
}
先实例化一个字符串对象,通过三种方式试图改变他的值。结果为:
只有函数没能完成任务,同样验证了我们的观点。