在java中搜索二维数组

jar*_*ryd 8 java arrays

如何通过二维数组搜索[] [Name]?

找到Name后,应返回Index,以便我可以更改该数组中的值.

[索引] [值].

此外,语法如何查找存储到找到的数组?[] [指数].循环索引并设置一个值.[0] [1] =等等.

谢谢

And*_*s_D 7

有时,将搜索放在单独的方法中会更容易,也更简洁:

 private Point find2DIndex(Object[][] array, Object search) {

    if (search == null || array == null) return null;

    for (int rowIndex = 0; rowIndex < array.length; rowIndex++ ) {
       Object[] row = array[rowIndex];
       if (row != null) {
          for (int columnIndex = 0; columnIndex < row.length; columnIndex++) {
             if (search.equals(row[columnIndex])) {
                 return new Point(rowIndex, columnIndex);
             }
          }
       }
    }
    return null; // value not found in array
 }
Run Code Online (Sandbox Code Playgroud)

这将仅返回第一场比赛.如果您需要全部,请收集列表中的所有点并在结尾处返回该列表.


用法:

private void doSomething() {
  String[][] array = {{"one", "1"},{"two","2"}, {"three","3"}};
  Point index = find2DIndex(array, "two");

  // change one value at index
  if (index != null)
     array[index.x][index.y] = "TWO";

  // change everything in the whole row
  if (index != null) {
     String[] row = array[index.x];
     // change the values in that row
  }

}
Run Code Online (Sandbox Code Playgroud)