简谈Java传值传引用

时间:2024-04-16 17:07:17

本随笔旨在强化理解传值与传引用

如下代码的运行结果
其中i没有改变,s也没有改变。
但model中的值均改变了。

i :100
s :hello
model :testchange
model2 :changeModel

java中的形参是复制实参在栈中的一份拷贝,所以在函数中改变形参是无法改变实参的值的,改变引用只是将形参所代表的引用指向另外的新的对象,而实参的引用还指向原来的对象,改变形参引用的对象当然会影响实参引用对象的值,因为他们的引用都指向同一个对象。
package newtest;

public class testman {

    class Model {
        int i = 0;
        public String s = "no value";

    }

    public static void changeInt(int i) {
        i = 10;
    }

    public static void changeString(String s) {
        s = "test";
    }

    public static void changeModel(Model model) {
        model.i = 10;
        model.s = "testchange";
    }

    public static void changeModel2(Model model) {
        model.i = 10;
        model.s = "changeModel";
    }

    public static void main(String[] args) {
        int i = 100;
        String s = "hello";
        Model model = new testman().new Model();
        Model model2 = new testman().new Model();

        changeInt(i);
        System.out.println("i :" + i);
        changeString(s);
        System.out.println("s :" + s);
        changeModel(model);
        System.out.println("model :" + model.s);
        changeModel2(model2);
        System.out.println("model2 :" + model2.s);

    }
}