我可以在 Java 中改变参数吗?

gat*_*tor 4 java oop mutation

在 C++ 中我可能会这样做:

sometype var = somevalue;
mutate(var);
// var is now someothervalue

void mutate(sometype &a) {
    a = someothervalue;
}
Run Code Online (Sandbox Code Playgroud)

Java中有类似的东西吗?

我正在尝试完成类似的事情:

Customer a;

public static void main(String[] args) {
    a = newCustomer("Charles");
    Customer b = null;
    mutate(b);
    System.out.println(b.getName()); // NullPointerException, expected "Charles"
}

void mutate(Customer c) {
    c = a;
}
Run Code Online (Sandbox Code Playgroud)

如果Customer是可变的,为什么会产生 NullPointerException?

Sur*_*tta 5

看起来您对可变性感到困惑。可变性只是改变对象状态。您在示例中展示的不仅仅是可变性。您通过将实例引用到其他某个实例 ( ) 来完全更改该实例=

sometype var = somevalue;
mutate(var);

void mutate(sometype a) {
    a = someothervalue; // changing a to someothervalue.
}
Run Code Online (Sandbox Code Playgroud)

什么是可变性

sometype var = somevalue;
mutate(var);
var.getChangeState() // just gives you the latest value you done in mutate method

    void mutate(sometype a) {
        varType someParamForA= valueX;
        a.changeState(someParamForA); // changing a param inside object a.
    }
Run Code Online (Sandbox Code Playgroud)

是的,如果可变对象在 Java 中完全有效。调用 mutate 方法后您可以看到变化。

基元的情况 ::

请记住,对于原语,您无法使用 Java 做到这一点。所有原始变量都是不可变的。

如果你想用 Java 实现同样的原语,你可以尝试这样的事情

int var = 0;
var = mutate(var);

int mutate(int a) {
    a = a + 1;
    return a;
}
Run Code Online (Sandbox Code Playgroud)