5.Java的值传递和引用传递问题

2016-08-03  本文已影响27人  gadfly_only

Java的值传递和引用传递问题

String的对象是不可修改的,如果真正要达到改变字符串的效果,我们需要使用StringBuilder来替代String。

要想不改变原来的对象可以继承Cloneable接口,实现其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();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读