在带有整数数组的 ArrayList 上使用 contains [英] Using contains on an ArrayList with integer arrays
问题描述
我有一个 ArrayList
,我向它添加了一个数组.
I have an ArrayList<int[]>
, and I add an array to it.
ArrayList<int[]> j = new ArrayList<int[]>();
int[] w = {1,2};
j.add(w);
假设我想知道 j
是否包含一个包含 {1,2}
的数组而不使用 w
,因为我会从另一个类调用它.因此,我创建了一个包含 {1,2}
的新数组...
Suppose I want to know if j
contains an array that has {1,2}
in it without using w
, since I will be calling it from another class. So, I create a new array with {1,2}
in it...
int[] t = {1,2};
return j.contains(t);
...但是即使 w
被添加到列表中,这也会返回 false,并且 w
包含与 t
完全相同的数组.
...but this would return false even though w
was added to the list, and w
contains the exact same array as t
.
有没有一种方法可以使用 contains ,这样我就可以检查 ArrayList
的元素之一是否具有数组值 {1,2}
?
Is there a way to use contains such that I can just check to see if one of the elements of the ArrayList
has the array value {1,2}
?
推荐答案
数组只能与 Arrays.equals() 进行比较.
Arrays can only be compared with Arrays.equals().
您可能想要一个 ArrayList 的 ArrayList.
You probably want an ArrayList of ArrayLists.
ArrayList<ArrayList<Integer>> j = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> w = new ArrayList<Integer>();
w.add(1); w.add(2);
j.add(w);
ArrayList<Integer> t = new ArrayList<Integer>();
t.add(1); t.add(2);
return j.contains(t); // should return true.
这篇关于在带有整数数组的 ArrayList 上使用 contains的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!