发现如果一个数组包含另一个数组的所有元素 [英] Finding if an array contains all elements in another array

查看:147
本文介绍了发现如果一个数组包含另一个数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是通过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.

这篇关于发现如果一个数组包含另一个数组的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆