String的對象是不可修改的袁翁,如果真正要達到改變字符串的效果株扛,我們需要使用StringBuilder來替代String漓概。
要想不改變原來的對象可以繼承Cloneable接口石挂,實現(xiàn)其clone()
public class demo {
public static void main(String[] args) {
String x = new String("way");
changeString(x);
System.out.println(x);
StringBuilder xx = new StringBuilder("ss");
changeStringBuilder(xx);
System.out.println(xx.toString());
Dest dest = new Dest();
dest.kk = 99;
changeObject1(dest);
System.out.println(dest.kk);
changeObject2(dest);
System.out.println(dest.kk);
}
public static void changeString(String x) {
x = "even";
}
public static void changeStringBuilder(StringBuilder x) {
x.append("even");
}
public static void changeObject1(Dest x) {
Dest yy = null;
try {
yy = (Dest) x.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
yy.kk = 100;
}
public static void changeObject2(Dest x) {
x.kk = 101;
}
}
class Dest implements Cloneable {
public Dest() {
}
public int kk = 0;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}