Integer进入到方法中无法改变方法外的引用的原因讲解

Integer是不可变对象。String也是不可变对象。

不可变对象: 每次对 该对象进行改变的时候其实都等同于生成了一个新的对象,然后将指针指向新的对象

如下图的String得例子:
在这里插入图片描述
由于在方法外变量的引用还是之前的变量地址,所以导致更改无法生效。

代码示例如下:

public class Mythread {
    
    public static <num> void main(String[] args) {
        Integer num = 0;
        add(num);
        System.out.println(num);
    }

    public static void add(Integer num){
      num++;
    }

}

输出结果还是0;

如果还是将变量代进去可以使用List,Stringbuffer等,我下面提供的是一个原子操作类,仅供参考。

public class Mythread {
    
    public static <num> void main(String[] args) {
        AtomicInteger num = new AtomicInteger(2);
        add(num);
        if (Integer.valueOf(3) == 3){
            System.out.println("将方法中的3带出来了");
        }
    }

    public static void add(AtomicInteger num){
      num.incrementAndGet();
    }

}

猜你喜欢

转载自blog.csdn.net/PhilsphyPrgram/article/details/119294088