java 传参的坑

 


    @Test
    public void testProps() {
        String str  = null;
        Car    car1 = null;
        Car    car2 = new Car(2, "car2");
        Car    car3 = new Car(3, "car3");

        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();

        map1.put("id", "123");
        map1.put("name", "xiaoa");

        //test
        test(map1, map2, str, car1, car2, car3);

        System.out.println(str);
        System.out.println(map1.size());
        System.out.println(map2.size());
    }

    private void test(Map<String, Object> map1, Map<String, Object> map2, String str, Car car1, Car car2, Car car3) {
        str = "good";
        map1.remove("id");

        //重新定义一个对象
        map2 = new HashMap<>();
        map2.put("test", 123);

        //新建对象
        car1      = new Car(1, "car1");
        //修改对象属性
        car2.name = "22222222222";
        //新建对象
        car3 = new Car(33, "car33333333");
    }

    class Car {
        public int    id;
        public String name;

        public Car(int id, String name) {
            this.id   = id;
            this.name = name;
        }
    }

//test 前

test后

只有car2 和 map1改变了

1) 基本类型和String 传入的是copy

2) 传入的对象,如果在方法内指向了新的对象,则不影响方法外的对象

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值