查找一个数组是否包含另一个数组中的所有元素 [英] Finding if an array contains all elements in another array

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

问题描述

我正在尝试遍历 2 个数组,外部数组比另一个数组长.它将遍历第一个数组,如果第二个数组不包含该 int,它将返回 false.但我无法弄清楚如何解决这个问题.这是我目前所拥有的:

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;
}

运行时出现此错误:

Cannot invoke contains(int) on the array type int[]

我想知道是否可以在不使用嵌套循环(如上)的情况下完成.我知道我做错了什么,如果有人可以帮助解决这个问题,那就太好了.此外,我不确定要在 int[] 的 java 文档中查找哪个类.

I am wondering if it can be done without using a nested loop (like above). I know I'm doing something wrong and if anyone could help on the matter it would be great. Also I wasn't sure what class to look for in the java doc for the int[].

推荐答案

您可以检查数组中较大的 outer 是否包含较小数组中的每个元素,即 inner:

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));
}

注意:此方法需要 Integer 类型才能工作.如果使用原语,则 Arrays.asList 将返回一个 List,其中包含一个 int[] 类型的元素.在这种情况下,调用 containsAll 不会检查数组的实际内容,而是比较原始 int 数组 Object 引用.

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天全站免登陆