简体   繁体   中英

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?

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. If it's possible and doesn't impact on performance, use an ArrayList or Vector and store Integers objects instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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