Welcome everyone

按值传递和按引用传递的小坑

java 汪明鑫 574浏览 0评论

按值传递没啥问题

/**
 * @author wmx
 * @date 2019-10-15
 */
public class Test4 {
    public static void main(String[] args) {
        int x = 2;
        triple(x);
        System.out.println("after triple "+ x);
    }

    private static void triple(int x) {
        x = x*3;
        System.out.println("in triple " + x);
    }
}

in triple 6
after triple 2

 

按引用传递

package pers.wmx.demo;

import lombok.Data;

/**
 * @author wmx
 * @date 2019-10-15
 */
public class Test5 {
    public static void main(String[] args) {
        Person p1 = new Person();
        p1.setName("王五");
        changeName(p1);
        System.out.println(p1);

        newName(p1);
        System.out.println(p1);
    }

    private static void changeName(Person person) {
        person.setName("王二麻子");
        System.out.println("changeName ->"+person);
    }

    private static void newName(Person person) {
        person = new Person();
        person.setName("赵六");
        System.out.println("newName ->"+person);
    }

}

@Data
class Person{
    String name;
}

changeName ->Person(name=王二麻子)
Person(name=王二麻子)
newName ->Person(name=赵六)
Person(name=王二麻子)

 

发现第二个new  对象后的修改不生效

从本质上说,对象的引用是按值传递的

因此我们可以修改参数对象内部的状态(称为按引用传递),但对参数对象重新赋值是没意义的

 

转载请注明:汪明鑫的个人博客 » 按值传递和按引用传递的小坑

喜欢 (0)

说点什么

您将是第一位评论人!

提醒
avatar
wpDiscuz