发现如果一个数组包含另一个数组的所有元素
我是通过2个阵列试图循环,外阵列不再那么其他。它将通过第一环路和如果第二阵列不包含INT它将返回一个假。但我无法弄清楚如何去这一点。这是我到目前为止有:
I am trying to loop through 2 arrays, the outer array is longer then the other. It will loop through the first and if the 2nd array does not contain that int it will return a false. But I cannot figure out how to go about this. This is what I have so far:
public boolean linearIn(int[] outer, int[] inner) {
for (int i = 0; i < outer.length; i++) {
if (!inner.contains(outer[i])) {
return false;
}
}
return true;
}
我收到此错误时运行:
I am getting this error when run:
Cannot invoke contains(int) on the array type int[]
我想知道是否可以在不使用嵌套循环(如上面)来完成。我知道我做错了什么,如果有人可以帮助对此事将是巨大的。此外,我不知道要寻找在Java文档什么类 INT []
。
您可以检查该数组外
较大包含较小的一个,即每一个元素内:
You could check that the larger of the arrays outer
contains every element in the smaller one, i.e. inner
:
public static boolean linearIn(Integer[] outer, Integer[] inner) {
return Arrays.asList(outer).containsAll(Arrays.asList(inner));
}
请注意:整数
类型都需要这种方式工作。如果使用原语,那么 Arrays.asList
将返回列表包含类型的单个元素
INT []
。在这种情况下,调用 containsAll
不会检查数组的实际内容,而是比较原始的 INT
阵列对象
引用。
Note: Integer
types are required for this approach to work. If primitives are used, then Arrays.asList
will return a List
containing a single element of type int[]
. In that case, invoking containsAll
will not check the actual content of the arrays but rather compare the primitive int
array Object
references.