java中二维数组的索引。

时间:2021-10-17 21:37:22

Is it possible to get the index of a 2D array? Suppose I have the following array

是否有可能得到二维数组的索引?假设我有以下数组

int[][] arr = {{41, 44, 51, 71, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};

And I want to get the index of 88, how to do it?

我想要得到88的指数,怎么做?

3 个解决方案

#1


3  

for (int i = 0 ; i < size; i++)
    for(int j = 0 ; j < size ; j++)
    {
         if ( arr[i][j] == 88)
         {
              `save this 2 indexes`
              break;
         }
    }

#2


2  

If they are not sorted, you will have to loop through all indexes [using double loop] and check if it is a match.

如果它们没有排序,您将不得不循环遍历所有索引(使用双循环)并检查它是否匹配。

int[][] arr = {{41, 44, 51, 71, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
for (int i = 0; i < arr.length; i++) { 
    for (int j = 0; j < arr[i].length; j++) { 
        if (arr[i][j] == 88) { 
            System.out.println("i=" + i + " j=" + j);
        }
    }
}

will result in:

将导致:

i=1 j=1
i=2 j=0

#3


0  

This is a primitive array, so it should be directly accessibly with the index:

这是一个原始数组,所以它应该与索引直接可访问:

int[] indexValue = arr[88];

EDIT:

编辑:

Sorry, reading it again, if you mean the indices of the item 88 then there are multiple occurrences of 88 so you would need to iterate through each index and look for a match in each, and also have the size of the arrays stored somewhere. If it's possible and doesn't impact on performance, use an ArrayList or Vector and store Integers objects instead.

抱歉,再读一遍,如果你指的是88的索引,那么就会有多次出现88,所以你需要遍历每个索引,并在每个索引中查找匹配项,并且还要有存储在某处的数组的大小。如果可能的话,使用ArrayList或Vector并存储整数对象。

#1


3  

for (int i = 0 ; i < size; i++)
    for(int j = 0 ; j < size ; j++)
    {
         if ( arr[i][j] == 88)
         {
              `save this 2 indexes`
              break;
         }
    }

#2


2  

If they are not sorted, you will have to loop through all indexes [using double loop] and check if it is a match.

如果它们没有排序,您将不得不循环遍历所有索引(使用双循环)并检查它是否匹配。

int[][] arr = {{41, 44, 51, 71, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
for (int i = 0; i < arr.length; i++) { 
    for (int j = 0; j < arr[i].length; j++) { 
        if (arr[i][j] == 88) { 
            System.out.println("i=" + i + " j=" + j);
        }
    }
}

will result in:

将导致:

i=1 j=1
i=2 j=0

#3


0  

This is a primitive array, so it should be directly accessibly with the index:

这是一个原始数组,所以它应该与索引直接可访问:

int[] indexValue = arr[88];

EDIT:

编辑:

Sorry, reading it again, if you mean the indices of the item 88 then there are multiple occurrences of 88 so you would need to iterate through each index and look for a match in each, and also have the size of the arrays stored somewhere. If it's possible and doesn't impact on performance, use an ArrayList or Vector and store Integers objects instead.

抱歉,再读一遍,如果你指的是88的索引,那么就会有多次出现88,所以你需要遍历每个索引,并在每个索引中查找匹配项,并且还要有存储在某处的数组的大小。如果可能的话,使用ArrayList或Vector并存储整数对象。