'contains' 方法对 ArrayList<int[]> 不起作用,还有其他方法吗? [英] The 'contains' method does not work for ArrayList<int[]>, is there another way?
问题描述
如果 ArrayList 还没有 int[]
,我想向它添加一个 int[]
,但由于某种原因,它不起作用.在这种情况下,arrlist 是 ArrayList
而 arr 是 int[]
.此代码位于 for 循环中,其中 arr 在循环中定义,因此 arr 中的值会发生变化.即使我打印出 arrlist 并且它有 arr,代码总是会说 arrlist 不包含 arr.是否有另一种方法来检查 ArrayList 是否包含 int[]
?
I want to add an int[]
to an ArrayList if it doesn't already have that int[]
, but for some reason, it's not working. In this case, arrlist is the ArrayList<int[]>
and arr is the int[]
. This code is in a for loop where arr is defined in the loop, so the values in arr changes. Even though I printed out arrlist and it had arr, the code would always say that arrlist didn't contain arr. Is there another way to check if an ArrayList contains an int[]
?
int n = scan.nextInt();
ArrayList<int[]> arrlist = new ArrayList<>();
int[][] coordinates = new int[n][2];
boolean[] isTrue = new boolean[n];
for (int j = 0; j < n; j++) {
int[] arr = new int[2];
arr[0] = coordinates[j][0];
arr[1] = coordinates[j][1];
if (arrlist.contains(arr)) {
isTrue[j] = true;
} else {
arrlist.add(arr);
}
}
推荐答案
考虑这段代码:
int[] a = {1, 2};
int[] b = {1, 2};
System.out.println(a.equals(b));
你明白为什么输出是false"吗?
Do you understand why the output is "false"?
这就是您的问题的原因:根据'equals'方法,内容相同的两个数组不相等,该方法在此处显式调用,并在您的 List<>
示例中隐式调用.
This is the cause of your problems: two arrays with equal content are not equal according to the 'equals' method, which is explicitly invoked here, and implicitly invoked in your List<>
example.
只要您想使用 int[]
数组,我看不到一个简单的解决方法.您不能定义 equals 方法.我认为,您最好的方法是根本不使用数组来包含坐标.
I don't see an easy fix as long as you want to use int[]
arrays. You cannot define an equals method. Your best approach, I think, is to not use an array at all to contain the coordinates.
定义一个类,其实例包含所需的两个整数:
Define a class whose instances hold the required two integers:
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
return o instanceof Point
&& x == ((Point) o).x
&& y == ((Point) o).y;
}
}
然后保留一个ArrayList
.包含"现在将按预期工作.
and then keep an ArrayList<Point>
. 'contains' will now work as expected.
(您还应该在 Point 类中定义 hashCode,但我跳过了它,它与答案并不直接相关).
(You should also define hashCode in class Point, but I skipped that, it is not immediately relevant to the answer).
这篇关于'contains' 方法对 ArrayList<int[]> 不起作用,还有其他方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!