是否可以修改 Java 中函数参数中发送的属性值?

Is it possible to modify the value of an attribute sent in argument of a function in Java?

我正在研究计算器,我在搜索如何优化我的代码。
问题是我有很多代码重复,因为我是在处理计算的第一个数字还是第二个数字。
所以我正在搜索是否可以修改函数参数中发送的属性值? (我想不是因为我无处看到答案)。

也许我表达不好,所以下面是一段代码来解释我在说什么:

public class MyClass
{
    private static int number1 = 1;
    private static int number2 = 2;

    public MyClass()
    {
        changeValueOf(number1, 3);
    }

    private static void changeValueOf(int number, int value)
    {
        //Change here the value of the correct field
    }

}

一种可能性是使用数组 来存储您的变量,而不是使用附加数字的单独变量。然后你会写 number[1] 而不是 number1 例如。您可以传递数组 index 数字来指示您指的是哪个变量。

public class MyClass
{
    private static int[] variables = {1, 2};

    public MyClass()
    {
        // change value of first variable
        changeValueOf(0, 3);

        // now variable[0] = 3
    }

    private static void changeValueOf(int number, int value)
    {
        variables[number] = value;
    }

}

首先可以修改方法内部的静态变量:

private static void changeValueOf(int value)
{
    number1 = value;
}

但我想这不是您想要的:)

在 Java(以及大多数其他语言)中,原始数据类型(intshortlong 等)按值传递,例如值的副本传递给方法(函数)。 以及通过引用传递的引用类型(对象,例如使用 new 运算符创建的对象)。因此,当您修改引用类型(对象)的值时,您可以看到外部作用域(例如,方法调用者)的变化。

所以,答案是否定的 - 您不能更改 int 的值,以便外部范围看到更新后的值。

但是,您可以用某个对象包装您的 int 值 - 它会更改其中的值:

public class Example {
    public static void main(String[] args) {
        Example app = new Example();

        // Could be static as well
        Holder val1 = new Holder(1);
        Holder val2 = new Holder(2);

        app.changeValue(val1, 7);

        System.out.println(val1.value); // 7
    }

    public void changeValue(Holder holder, int newValue) {
        holder.value = newValue;
    }

    static class Holder {
        int value;
        Holder(int value) {
            this.value = value;
        }
    }
}

此外,您可以创建一个包含 2 个值的数组并在方法内更新它们,但这不是很好的方法 IMO

最后,您可以 return 更新值并将其分配给您的变量:

public class Example {
    private static int number1 = 2;
    private static int number2 = 3;

    public static void main(String[] args) {
        Example app = new Example();
        
        number1 = app.mul(number1, 7);
        number2 = app.mul(number2, 7);

        System.out.println(number1); // 14
        System.out.println(number2); // 21
    }

    public int mul(int a, int b) {
        return a * b;
    }

}