开发者

Testing for equality in a two-dimensional array in Java

How would I find all 开发者_JAVA技巧matching elements in a two-dimensional array in Java?


Basically you just iterate through the rows and columns, check if the content of the addressed cell is equal (!) in both matrices and store the result to another matrix, which is the result of your operation.

Don't forget to implement the mandatory checks for the matrices, otherwise the algorithm will definitly crash in case you provide 'illegal arguments'.

Variations: if you need java primitives (int or float), change the type of the arrays and do not use equals to compare but the == operator.

private boolean[][] findMatches(Object[][] array1, Object[][] array2) {
  if (notComparable(array1, array2) {
   return null;
  }

  boolean[][] result = new boolean[array1.length, array1[0].length];
  for (int row = 0; row < array1.length; row++) {
    for (int column = 0; column < array1.length; column++) {
      if (array1[row][column].equals(array2[row][column]) {
        result[row][column] = true;
      }
    }
  }
  return result;

}

private boolean notComparable(Object[][] array1, Object[][] array2) {

  // dummy implementation - add your checks here to guarantee
  // that the arrays are not null, not empty and of same size in each row

  return false;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜