1

私は方法を持っています:

public static void MutableInt (int newValue) {
    AtomicInteger atomicInteger;
    atomicInteger = new AtomicInteger(10);
    newValue = atomicInteger.get();
}

次に、メインで呼び出します。

    int x=3;
    MutableInt(x);
    System.out.println("After invoking MutableInt method, x = " + x);

結果はまだ 3 です。この方法で int を変更することは可能ですか?

4

3 に答える 3

1

いいえ。mutableInt()の値の中で何をしても、ままにxなります3。これを変更する唯一の方法は、メソッドが int を返して に代入するようxにするか、xそれ自体を変更可能なオブジェクト ( などAtomicInteger) に変更することです。

于 2016-09-12T17:56:16.733 に答える
0

FIst of all, you're passing a primitive to the method, not a reference to an instance of an object. Even with autowiring, if you set the int variable to something else inside the method, since your not returning anything, the variable outside the scope of the method won't be changed.

If you passed an Integer object instead, the value of the Integer outside the method would be modified if you changed it inside the method, as long as it was not final in the signature of the method.

The fact that your creating an intermediate AtomicInteger inside the method isn't important, since it only exists on the scope of the method.

于 2016-09-12T18:04:07.247 に答える
0

あまり。Java 引数は、参照ではなく値によって渡されるため、メソッド内の変数を変更しても、その外側で宣言された変数には何も影響しません。次のようなことができます

public static int MutableInt (int newValue) {
    AtomicInteger atomicInteger;
    atomicInteger = new AtomicInteger(10);
    return atomicInteger.get();
}

int x = MutableInt(3);
System.out.println("After invoking MutableInt method, x = " + x);
于 2016-09-12T17:59:19.647 に答える