访问嵌套For循环索引

时间:2016-05-07 00:55:04

标签: java

java中的for循环是否访问adjacencyMatrix的所有索引或仅执行

adjacencyMatrix[1][1]; 
adjacencyMatrix[2][2]; 
adjacencyMatrix[3][3]; 
adjacencyMatrix[4][4]; 

for (int i = 1; i <= number_of_nodes; i++)
        for (int j = 1; j <= number_of_nodes; j++)
            adjacencyMatrix[i][j] = adjacency_matrix[i][j];

由于

2 个答案:

答案 0 :(得分:0)

这将 not 访问数组的所有索引,因为数组索引从0开始,而不是1.换句话说,2D数组的第一个元素将是 adjacencyMatrix [0] [ 0] 所以你应该从0开始你的两次迭代。

如果数组的长度为5,那么最大的索引将是4,所以要小心迭代的距离。

例如,如果你这样做:

for (int i = 1; i <= number_of_nodes; i++)
    for (int j = 1; j <= number_of_nodes; j++)
        adjacencyMatrix[i][j] = adjacency_matrix[i][j];

然后它会访问:

adjacencyMatrix[1][1]; 
adjacencyMatrix[1][2]; 
adjacencyMatrix[2][1]; 
adjacencyMatrix[2][2]; 

etc...

如果您这样做:

for (int i = 1; i <= number_of_nodes; i++)
        adjacencyMatrix[i][i] = adjacency_matrix[i][i];

然后它会访问:

adjacencyMatrix[1][1]; 
adjacencyMatrix[2][2]; 
adjacencyMatrix[3][3]; 
adjacencyMatrix[4][4]; 

答案 1 :(得分:-2)

for (int i = 0; i < number_of_nodes; i++)
    for (int j = 0; j < number_of_nodes; j++)
        adjacencyMatrix[i][j] = adjacency_matrix[i][j];