0
function(testInPlaceInteger(a))を呼び出した後int intの値は変わりませんが、関数squareArrayInPlaceを呼び出した後にint [] arrが変化します。 int型の値が変わらないのはなぜですか?
次は私のコードです:はint []では動作しますが、javaではintではありません
public class Test {
public static void main(String[] args) {
int a = 5;
int[] arr = new int[] {3, 4};
Test test = new Test();
test.testInPlaceInteger(a);
test.squareArrayInPlace(arr);
System.out.println(a);
for (int i : arr) {
System.out.println(i);
}
}
public void testInPlaceInteger(int num) {
num *= num;
}
public void squareArrayInPlace(int[] intArray) {
for (int i = 0; i < intArray.length; i++) {
intArray[i] *= intArray[i];
}
}
}
は出力:
5
9
16
プリミティブは値渡しのみです –
@PavneetSingh - 非プリミティブにも適用されます。 –
@StephenCええ、ただオブジェクトをシンプルに保つために、プリミティブは機能呼び出しの間に状態と動作を維持できます:) –