我的代码中有一个理解上的问题,但是在下面的代码中标记的一个非常特定的行中:

公共班级主要{

public static void main(String[] args) {

    // TODO Auto-generated method stub

    arrayTest();

}

public static void printArray(int [] a) {
    for(int i= 0; i < a.length; i++) {
        System.out.println(a[i] + "");
    }
}
public static void arrayTest() {
    int [] numbers = new int [4];
    numbers[0] = 1;
    numbers[1] = 2;
    numbers[2] = 3;
    numbers[3] = 4;
    numbers[numbers[1]] = numbers.length + numbers[0];  // <= what is exactly happening here?
    printArray(numbers);
} }


输出如下所示:
1个
2
5
4

为什么数字5在数字[2]上而不是数字[1]?

在此先感谢您的帮助。

最佳答案

为了简单起见,让我们使用其他值:

numbers is [10,20,30,40]
At index -> 0  1  2  3
   values-> 10 20 30 40

number[at index 1] -> 20 (Here 1 is the index, 20 is the value)

number[number[1]] -> number[20] -> OutOfBoundsError as the array size is 4
number[number[0]] -> number[10] -> OutOfBoundsError as the array size is 4


在您的情况下:

numbers[numbers[1]] = number.length + numbers[0];
numbers[2] = 4 + 1
numbers[2] = 5

09-10 03:38
查看更多