检查ArrayList是否包含一个Array对象 [英] Check if ArrayList contains an Array Object
问题描述
是否可以检查ArrayList是否包含对象数组?例如我有一个arrayList
Is there a way to check if an ArrayList contains an array of objects? For example I have an arrayList
ArrayList<Integer[]> myList = new ArrayList<Integer[]>();
mylist.add(new Integer[]{5,5});
mylist.add(new Integer[]{1,1});
我想检查它是否包含特定的Integer数组.喜欢:
I would like to check if it contains a specific Integer array. Like:
Integer[] myArray = new Integer[]{5,5};
如果我使用myList.containts(myArray);它应该返回true,但是它检查是否包含Integer对象,而不是数组Values.
if I use the myList.containts(myArray); it should return true, but it checks if the Integer object is containted, not the array Values.
有没有办法检查这些值?
Is there a way to check the values?
推荐答案
java.util.Arrays
包含几种与数组相关的实用程序方法,包括 Arrays.deepEquals(Object [] a1,Object [] a2)
.您可以根据该测试扫描列表以查找与 new Integer [] {5,5}
相等的任何元素:
java.util.Arrays
contains several array-related utility methods, including Arrays.deepEquals(Object[] a1, Object[] a2)
. You can scan the list looking for any element that is equal to new Integer[]{5,5}
according to that test:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
ArrayList<Integer[]> myList = new ArrayList<Integer[]>();
myList.add(new Integer[] { 5, 5 });
myList.add(new Integer[] { 1, 1 });
System.out.println(deepContains(myList, new Integer[] { 5, 5 }));
System.out.println(deepContains(myList, new Integer[] { 5, 3 }));
}
public static boolean deepContains(List<Integer[]> list, Integer[] probe) {
for (Integer[] element : list) {
if (Arrays.deepEquals(element, probe)) {
return true;
}
}
return false;
}
}
这篇关于检查ArrayList是否包含一个Array对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!