简体   繁体   English

Java 2D数组的索引

[英]Index of 2D array in java

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的指数,怎么做?

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

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

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. 抱歉,再次阅读,如果您是指项目88的索引,那么会出现88次,因此您需要遍历每个索引并在每个索引中寻找匹配项,并且还需要将数组的大小存储在某个位置。 If it's possible and doesn't impact on performance, use an ArrayList or Vector and store Integers objects instead. 如果可能并且不影响性能,请使用ArrayList或Vector并存储Integers对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM