【考点】:java中只有值传递,引用类型也只是将对象地址传了过去
String类中没有操作底层char数组的方法,+=时会产生新的对象,StringBuilder类中有操作char数组的操作,append后不会产生新对象
【解决方法】所有这类问题都可以用画图来解决,只要是new了,就是产生了新对象,就会在堆中分配内存,只有gc时才回收
只要是方法中的局部变量,就是在栈中分配内存,方法运行完后,自动回收
public class Test {
public static void exchangeString(String s1, String s2){
s1 = s2;
s2 = new String();
s1 += " world";
s2 += " world";
}
public static void exchangeSB(StringBuilder s1, StringBuilder s2){
s1 = s2;
s2 = new StringBuilder();
s1.append(" world");
s2.append(" world!");
}
public static void function(int[] c){
c[0] = -1000;
}
public static void main(String[] args) {
String s1 = new String("good");
String s2 = new String("bad ");
exchangeString(s1, s2);
System.out.println(s1.toString()); //good
System.out.println(s2.toString()); //bad
StringBuilder stringBuilder1 = new StringBuilder("good");
StringBuilder stringBuilder2 = new StringBuilder("bad ");
exchangeSB(stringBuilder1, stringBuilder2);
System.out.println(stringBuilder1.toString()); //good
System.out.println(stringBuilder2.toString()); //bad world
int[] a = new int[3];
int[] b = a;
b[2] = 1000;
System.out.println(a[2]);//1000
System.out.println(b[2]);//1000
function(b);
System.out.println(Arrays.toString(a)); //[-1000, 0, 1000]
}
}