Java-判断数组的位置变化

标签 java arrays count numbers position

我的代码中有一个理解问题,但在一个非常具体的行中,在下面的代码中进行了标记:

公共(public)类主要{

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 出现在numbers[2]上而不是numbers[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

关于Java-判断数组的位置变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48802155/

相关文章:

java - 为什么 CVM 被称为 C 虚拟机,来自 SUN for CDC (J2ME)?

c - 存储数组的子集

count - BigQuery subsselect 示例(计数和总和)

java - 使用两个 Yugabyte 实例的多 dc 复制

java - 如何在不使用太多 if 子句的情况下获取类型?

javascript - 在 .splice() 之后重置 Angular 函数中的数组副本

c - 用完 ram 声明全局二维数组问题

sql - MySQL COUNT 无法统计

java - 标记化和计数标记

java - 自定义 spring boot 自动配置未检测到 bean