这是我创建的有效方法。我使用了Arrays.deepEquals。它检查 int[][] 是否位于 int[][] 之外的 ArrayList 内。谢谢托马斯提供解决方案!
public boolean contains(int[][]matrix1, List<int[][]> matrice){
boolean contains = false;
for(int[][] m : matrice){
if(Arrays.deepEquals(m, matrix)){
contains = true;
index = matrice.indexOf(m);
}
}
return contains;
}
我有以下代码。我想从与矩阵具有相同值的矩阵中获取索引。我认为它不起作用,因为我正在检查引用而不是值。我只是不知道该怎么做。
List<int[2][2]> matrice = new ArrayList<int[][]>();
int[][] matrix = new int[2][2]
public void testMethod(){
// here matrix gets a value
matrix = {{1,4}{3,2}};
//Here List matrice gets filled with different matrice (4x)
...
//add a copy of matrix to matrice
matrice.add(copy2dArray(matrix));
int index = matrice.indexOf(matrix);
System.out.println("matrix ->"Arrays.deepToString(matrix));
System.out.println("matrice[4] ->"Arrays.deepToString(matrice[4]));
System.out.println("index = "+index);
System.out.println(matrice.contains(matrix));
}
private int[][] copy2dArray(int[][] original){
int[][] copy = new int[original.length][];
for(int i = 0; i < original.length; i++){
copy[i] = Arrays.copyOf(original[i], original[i].length);
}
return copy;
}
输出:
matrix -> [[1,4],[3,2]]
matrice[4] -> [[1,4],[3,2]]
index = -1
false
输出应该是:
matrix -> [[1,4],[3,2]]
matrice[4] -> [[1,4],[3,2]]
index = 4
true
最佳答案
问题在于 ArrayList.indexOf()
(与大多数其他实现一样)迭代元素并对每个元素调用 equals()
直到有一个匹配为止。然后返回其索引,在您的示例中应为 0(而不是 4)。
但是,数组没有定义自己的 equals()
实现,因此使用 Object
中定义的默认实现,仅当数组是完全相同的实例(由于您复制了数组,所以它们不是)。
要解决此问题,您可以使用包含数组并适当实现 equals()
(和 hashCode()
)的包装器。该“包装器”可以称为Matrix
,并且可能还会带来更好的设计;)
示例:
class Matrix {
int[][] theCells;
public boolean equals(Object o) {
//compare the indivual arrays, e.g. by using `Arrays.deepEquals()`,
//which takes care of multidimensional arrays
}
}
List<Matrix> matrices = new ArrayList<>();
关于java - 如何在indexOf中使用int[][]之外的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35896240/