Caveman42 Caveman42 - 2 years ago 122
Java Question

Finding if an array contains all elements in another array

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[]

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

Answer Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download