通过应在 java 中修改的方法后未修改 char 数组

char array not modified after passing trough a method that should modify it in java

你好,我在下面写下的代码有问题。据我所知,到目前为止传递给该方法的是 charArray 的内存引用,因此变量 charArray 和 tabCar 应该指向相同的内存位置。因此应该可以看到在我的方法 reverseArray 中所做的修改,但不知何故 2 print 语句显示相同的数组...有人可以向我解释为什么吗?

public static void reverseArray(char[] tabCar){
    int lastPlace = tabCar.length - 1;
    for(int i = 0 ; i < tabCar.length ; i++){
        char tempChar = tabCar[i];
        tabCar[i] = tabCar[lastPlace - i];
        tabCar[lastPlace - i] = tempChar;
    }
}

public static void main(String[] args) {
    char[] charArray = {'a','b','c','d','e','f'};
    System.out.println("Before reverseArray : " + Arrays.toString(charArray));
    reverseArray(charArray);
    System.out.println("After reverseArray : " + Arrays.toString(charArray));
}

因为你是 运行 循环直到 tabCar.length 发生的事情是一旦 i 值超过 tabCar 就会恢复更改。lenght/2 即:

a b c d e f --->original
f b c d e a ---> i=0
f e c d b a ---> i=1
f e d c b a ---> i=2
f e c d b a ---> i=3 (reverting the changes)
f b c d e a ---> i=4
a b c d e f ---> i=5

所以当它到达一半时你应该停止循环(tabCar.length/2)

public static void reverseArray(char[] tabCar) {
    int lastPlace = tabCar.length - 1;
    for (int i = 0; i < tabCar.length / 2; i++) {
        char tempChar = tabCar[i];
        tabCar[i] = tabCar[lastPlace - i];
        tabCar[lastPlace - i] = tempChar;
    }
}