问题是数组没有覆盖equals方法,所以它们具有默认实现的行为,即:
150 public boolean equals(Object obj) {
151 return (this == obj);
152 }
这是包含调用以查看列表是否包含您搜索的元素。
如果你拿这个:
List<String[][]> l = new ArrayList<>();
l.add(new String[][]{{"one"},{"two"}});
String[][] arr = {{"one"},{"two"}};
System.out.println(l.contains(arr)); //false
它输出false,因为这两个数组不指向同一个内存位置。
您可以使用
Arrays.deepEquals 创建一个辅助方法:
static boolean contains(List<String[][]> l, String[][] arr){
for(String[][] array : l){
if(Arrays.deepEquals(array, arr)){
return true;
}
}
return false;
}
...
System.out.println(contains(l, arr)); //true
另一种可能性是使用一个类来保存您的数组,然后覆盖 equals。
class MyArrayHolder {
private String[][] arr;
public MyArrayHolder(String[][] arr){
this.arr = arr;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.deepHashCode(arr);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyArrayHolder other = (MyArrayHolder) obj;
if (!Arrays.deepEquals(arr, other.arr))
return false;
return true;
}
}
然后使用List<MyArrayHolder>
public static void main(String[] args) throws Exception{
List<MyArrayHolder> l = new ArrayList<>();
l.add(new MyArrayHolder(new String[][]{{"one"},{"two"}}));
String[][] arr = {{"one"},{"two"}};
System.out.println(l.contains(new MyArrayHolder(arr))); //true
}