Java int[][] 数组 - 迭代和查找值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/474451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:06:07  来源:igfitidea点击:

Java int[][] array - iterating and finding value

javaarraysiteration

提问by Tray

I have an array in the form of 'int[][]' that represents the co-ordinates of a small grid. Each co-ordinate has been assigned its own value. eg array[0][4] = 28......

我有一个 ' int[][]'形式的数组,它表示一个小网格的坐标。每个坐标都被分配了自己的值。例如array[0][4] = 28......

I have two questions. Firstly, how do I iterate through all the stored values. Secondly, I want to be able to input a value and have its specific co-ordinates in the grid returned. What would be the best way to approach this?

我有两个问题。首先,我如何遍历所有存储的值。其次,我希望能够输入一个值并返回其在网格中的特定坐标。解决这个问题的最佳方法是什么?

Thank you for any help!

感谢您的任何帮助!

采纳答案by Jon Skeet

You can iterate with either for loops or enhanced for loops:

您可以使用 for 循环或增强的 for 循环进行迭代:

for (int row=0; row < grid.length; row++)
{
    for (int col=0; col < grid[row].length; col++)
    {
        int value = grid[row][col];
        // Do stuff
    }
}

or

或者

// Note the different use of "row" as a variable name! This
// is the *whole* row, not the row *number*.
for (int[] row : grid)
{
    for (int value : row)
    {
         // Do stuff
    }
}

The first version would be the easiest solution to the "find the co-ordinates" question - just check whether the value in the inner loop is correct.

第一个版本将是“找到坐标”问题的最简单解决方案 - 只需检查内循环中的值是否正确。

回答by user54579

to iterate over the values use loops:

迭代值使用循环:

 int[][] matrix   
 //...
 for(int row[] : matrix)
     for(int cell : row){
      //do something with cell
    }

to access the coordinates based on the value you would need some sort of double hashmap (look a at java.util.HashMap) but i am aware of nothing that does so directly

要根据值访问坐标,您需要某种双哈希图(查看 java.util.HashMap),但我不知道直接这样做

回答by Herms

Unless your grid is sorted in some way then you probably won't do any better than a brute force search.

除非您的网格以某种方式排序,否则您可能不会比蛮力搜索做得更好。

For iterating, I think it would be something like this (syntax might be off a bit, I haven't dealt with arrays in java for a while.):

对于迭代,我认为它会是这样的(语法可能有点偏差,我已经有一段时间没有在 Java 中处理数组了。):

int[][] grid;  // just assuming this is already assigned somewhere

for(int x = 0 ; x < grid.length ; x++) {
  int[] row = grid[x];
  for(int y = 0 ; y < row.length ; y++) {
    int value = row[y];
    // Here you have the value for grid[x][y] and can do what you need to with it
  }
}

For searching you'd probably need to use that to iterate, then return once you've found it.

对于搜索,您可能需要使用它进行迭代,然后在找到后返回。

If you might be looking up the position of the same value multiple times then you might want to memoize the results using a hashtable.

如果您可能多次查找相同值的位置,那么您可能需要使用哈希表来记忆结果。

回答by Kevin Loney

To iterate over all the elements in the grid try this:

要遍历网格中的所有元素,请尝试以下操作:

int grid[][] = new int[10][10];

for(int i = 0; i < grid.length(); ++i) {
    for(int j = 0; j < grid[i].length(); ++j) {
        // Do whatever with grid[i][j] here
    }
}

回答by David Z

There's generally no way to find the specific coordinates of a particular value except by going through the array and searching for it. However, if the values in the array are guaranteed to be unique (i.e. each value only occurs in one cell), you could maintain a separate array as an index, which stores the coordinates of each value indexed by the value.

除了遍历数组并搜索它之外,通常无法找到特定值的特定坐标。但是,如果数组中的值保证是唯一的(即每个值只出现在一个单元格中),您可以维护一个单独的数组作为索引,它存储由该值索引的每个值的坐标。

回答by alexwood

Use nested for loops to iterate over the x and y dimensions, which lets you go over each value, one at a time.

使用嵌套的 for 循环遍历 x 和 y 维度,这样您可以一次遍历每个值。

For inputting a value, just do the same as above, but look for a match to your requested value.

要输入值,只需执行与上述相同的操作,但要查找与您请求的值匹配的值。

回答by Bill K

You'll be happiest if you block all these collections inside a single class and don't expose them in any way.

如果您将所有这些集合阻塞在一个类中并且不以任何方式公开它们,您会最高兴。

This means moving your search and lookup routines into this class as well.

这意味着将您的搜索和查找例程也移动到这个类中。

For storage, everybody's covered iterating, add a hashtable and a lookup. I put this comment on nickolai's post:

对于存储,每个人都涵盖了迭代、添加哈希表和查找。我把这个评论放在 nickolai 的帖子上:

Store new Integer(ix + iy * 1000) as the value in your hash table. If your y index can go over 1000 use a bigger number--ints are really big. To get it back use ix=val%1000, iy=val/1000.

将 new Integer(ix + iy * 1000) 存储为哈希表中的值。如果您的 y 索引可以超过 1000,请使用更大的数字——整数真的很大。要取回它,请使用 ix=val%1000, iy=val/1000。

If your array and hashtable are encapsulated in the same class, the rest of your code will be pretty easy to write and a lot cleaner.

如果你的数组和哈希表被封装在同一个类中,你的其余代码将非常容易编写并且更清晰。