Java 如何在方法中直接修改传参值?

以下代码在运行后,结果不会是“30” ,反而依然是“10” , 因为tripleValue()方法其实只是将传入的“present”值复制为“x”变量,所以对“x”的操作不会对“present”有任何影响

 public static void main(String[] args) {
        int persent = 10;
        tripleValue(persent);
        System.out.println(persent);
    }

    public static void tripleValue(int x) {
        x = 3 * x;
    }

 以下是几种可以改变原来值的方法:

在Java中,数组是可变对象,而不是像包装类(如Integer)那样是不可变的。这意味着可以通过引用数组并直接修改数组元素来改变数组的内容。

当将数组作为参数传递给方法时,实际上传递的是数组的引用(内存地址)。在方法内部,可以使用这个引用来直接访问和修改数组的元素。

 public static void main(String[] args) {
        int[] array = {10};
        tripleValue(array);
        System.out.println(array[0]);
    }
    
    public static void tripleValue(int[] array) {
        array[0] = 3 * array[0];
    }

另一种是自己定义包装类: 

public class Test {
    public static void main(String[] args) {
        MyInteger value = new MyInteger(10);
        tripleValue(value);
        System.out.println(value.getValue());
    }
    
    public static void tripleValue(MyInteger value) {
        int newValue = 3 * value.getValue();
        value.setValue(newValue);
    }
}

class MyInteger {
    private int value;
    
    public MyInteger(int value) {
        this.value = value;
    }
    
    public int getValue() {
        return value;
    }
    
    public void setValue(int value) {
        this.value = value;
    }
}

考试中可能出现这种题:

public class Example{
    String str=new String("hello");
    char[]ch={'a','b'};
    public static void main(String args[]){
        Example ex=new Example();
        ex.change(ex.str,ex.ch);
        System.out.print(ex.str+" and ");
        System.out.print(ex.ch);//最终结果为:“hello and cb”
    }
    public void change(String str,char ch[]){
        str="test ok";//不会更改原来变量
        ch[0]='c';//会更改原来变量
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_46146935/article/details/130731708