0
在调用函数(squareInrayInPlace)后,int a的值在调用函数(testInPlaceInteger(a))后保持不变,但对于int [] arr更改。为什么int值不变?
以下是我的代码:适用于int [],但不适用于int中的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是的,但只是为了保持简单,对象可以在整个函数调用中保持它的状态和行为,而原始不能:) –