英文:
Find specific int[] element inside ArrayList<int[]>
问题
我正在尝试查找是否在一个ArrayList<int[]>中存在特定的int[],但是当我使用.contains(value)方法时,它总是返回false。我知道正在比较的是引用值。
我已经尝试将每个数组元素转换为原始哈希,并将其存储在另一个ArrayList中,但这个过程太长,当我提交我的代码时,我超过了时间限制。
英文:
I'm trying to find if a specific int[] exists within an ArrayList<int[]>, but when I use the method
.contains(value) it always returns false. I know that what is getting compared are the reference values.
I've tried converting each array element into a primitive hash, and storing it in another arrayList, but this process takes too long and when I submit my code I go past the time limit.
答案1
得分: 2
你已经确定,List.contains
会根据 Object.equals
来判断包含的元素和给定的元素是否相等返回结果。问题是,数组不是按你期望的方式实现的。你应该使用 Arrays.equals
代替:
for (int[] element : myList) {
if (Arrays.equals(element, target)) {
// 找到了!
}
}
英文:
As you already determined, List.contains
will return results if the contained element and the given element are equal according to Object.equals
. The problem is, arrays don't implement that the way you'd expect. You want Arrays.equals
instead:
for (int[] element : myList) {
if (Arrays.equals(element, target)) {
// found it!
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论