检查 ArrayList 是否包含一个数组对象 [英] 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});
我想检查它是否包含特定的整数数组.喜欢:
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,对象[] 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 是否包含一个数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!