Find specific int[] element inside ArrayList

huangapple go评论92阅读模式
英文:

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!
  }
}

huangapple
  • 本文由 发表于 2023年7月23日 18:02:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定