发现如果一个数组包含另一个数组的所有元素

编程入门 行业动态 更新时间:2024-10-25 22:23:55
本文介绍了发现如果一个数组包含另一个数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

发现如果一个数组包含另一个数组的所有元素

本文发布于:2023-10-27 11:44:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533260.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   发现

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!