Best way to check if an Array of primitives contains all of the primitives in another Array

Viewed 215

I'm looking for the best way to check if an Array of primitives contains all of the primitives in another Array in Java. For instance:

int[] a = new int[]{1,2};
int[] b = new int[]{1,2,3,4,5};
int[] c = new int[]{2,4,6};

containsAll(b, a); //true
containsAll(a, b); //false
containsAll(c, b); //false

Where containsAll is a function that check if inside the first parameter there is the second parameter!!! I don't want to convert my arrays of int in arrays of Integer in order to use the following method:

Arrays.asList(a).containsAll(Arrays.asList(b))

Because I think that if the arrays are huge, it would be a big waste of performance!!! But maybe I'm wrong and the best solution is that one... Have you got any idea?

1 Answers

The containsAll() method from the Java collections framework effectively does the two nested loops, so you'll waste performance converting to ArrayList<Integer> or Integer[] with Arrays.asList() and using containsAll().

Doing two nested loops over your int[] arrays yourself will definitely beat that.

And if you have additional information (e.g. sorted arrays, repeated use of the same arrays, typical sizes of the arrays), a more performant algorithm might be possible.

Related